print warning when topdir looks like a real dir
[build.git] / module-tag.py
1 #!/usr/bin/python -u
2
3 subversion_id = "$Id$"
4
5 import sys, os, os.path
6 import re
7 import time
8 from glob import glob
9 from optparse import OptionParser
10
11 def prompt (question,default=True):
12     if default:
13         question += " [y]/n ? "
14     else:
15         question += " y/[n] ? "
16     try:
17         answer=raw_input(question)
18         if not answer:
19             return default
20         elif answer[0] in [ 'y','Y']:
21             return True
22         elif answer[0] in [ 'n','N']:
23             return False
24         else:
25             return prompt(question,default)
26     except KeyboardInterrupt:
27         print "Aborted"
28         return False
29     except:
30         raise
31
32 class Command:
33     def __init__ (self,command,options):
34         self.command=command
35         self.options=options
36         self.tmp="/tmp/command-%d"%os.getpid()
37
38     def run (self):
39         if self.options.verbose:
40             print '+',self.command
41             sys.stdout.flush()
42         return os.system(self.command)
43
44     def run_silent (self):
45         if self.options.verbose:
46             print '+',self.command,' .. ',
47             sys.stdout.flush()
48         retcod=os.system(self.command + " &> " + self.tmp)
49         if retcod != 0:
50             print "FAILED ! -- output quoted below "
51             os.system("cat " + self.tmp)
52             print "FAILED ! -- end of quoted output"
53         elif self.options.verbose:
54             print "OK"
55         os.unlink(self.tmp)
56         return retcod
57
58     def run_fatal(self):
59         if self.run_silent() !=0:
60             raise Exception,"Command %s failed"%self.command
61
62     # returns stdout, like bash's $(mycommand)
63     def output_of (self,with_stderr=False):
64         tmp="/tmp/status-%d"%os.getpid()
65         if self.options.debug:
66             print '+',self.command,' .. ',
67             sys.stdout.flush()
68         command=self.command
69         if with_stderr:
70             command += " &> "
71         else:
72             command += " > "
73         command += tmp
74         os.system(command)
75         result=file(tmp).read()
76         os.unlink(tmp)
77         if self.options.debug:
78             print '+',self.command,'Done',
79         return result
80
81 class Svnpath:
82     def __init__(self,path,options):
83         self.path=path
84         self.options=options
85
86     def url_exists (self):
87         if self.options.verbose:
88             print 'Checking url',self.path
89         return os.system("svn list %s &> /dev/null"%self.path) == 0
90
91     def dir_needs_revert (self):
92         command="svn status %s"%self.path
93         return len(Command(command,self.options).output_of(True)) != 0
94     # turns out it's the same implem.
95     def file_needs_commit (self):
96         command="svn status %s"%self.path
97         return len(Command(command,self.options).output_of(True)) != 0
98
99 class Module:
100
101     # where to store user's config
102     config_storage="CONFIG"
103     # 
104     configKeys=[ ('svnpath',"Enter your toplevel svnpath (e.g. svn+ssh://thierry@svn.planet-lab.org/svn/)"),
105                  ('username',"Enter your firstname and lastname for changelogs"),
106                  ("email","Enter your email address for changelogs"),
107                  ("build", "Enter the name of your build module - in general 'build'") ]
108     config={}
109
110     svn_magic_line="--This line, and those below, will be ignored--"
111     
112     redirectors=[ ('module_name_varname','name'),
113                   ('module_version_varname','version'),
114                   ('module_taglevel_varname','taglevel'), ]
115
116     def __init__ (self,name,options):
117         self.name=name
118         self.options=options
119         self.moddir="%s/%s"%(options.workdir,name)
120         self.trunkdir="%s/trunk"%(self.moddir)
121         self.varmatcher=re.compile("%define\s+(\S+)\s+(\S*)\s*")
122
123
124     def run (self,command):
125         return Command(command,self.options).run()
126     def run_fatal (self,command):
127         return Command(command,self.options).run_fatal()
128     def run_prompt (self,message,command):
129         if not self.options.verbose:
130             question=message
131         else:
132             question="Want to run " + command
133         if prompt(question,True):
134             self.run(command)            
135
136     @staticmethod
137     def init_homedir (options):
138         topdir=options.workdir
139         if options.verbose:
140             print 'Checking for',topdir
141         storage="%s/%s"%(topdir,Module.config_storage)
142         # sanity check. Either the topdir exists AND we have a config/storage
143         # or topdir does not exist and we create it
144         # to avoid people use their own daily svn repo
145         if os.path.isdir(topdir) and not os.path.isfile(storage):
146             print """The directory %s exists and has no CONFIG file
147 If this is your regular working directory, please provide another one as the
148 module-* commands need a fresh working dir. Make sure that you do not use 
149 that for other purposes than tagging"""%topdir
150             sys.exit(1)
151         if not os.path.isdir (topdir):
152             # prompt for login or whatever svnpath
153             print "Cannot find",topdir,"let's create it"
154             for (key,message) in Module.configKeys:
155                 Module.config[key]=raw_input(message+" : ").strip()
156             Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
157             # store config
158             f=file(storage,"w")
159             for (key,message) in Module.configKeys:
160                 f.write("%s=%s\n"%(key,Module.config[key]))
161             f.close()
162             if options.debug:
163                 print 'Stored',storage
164                 Command("cat %s"%storage,options).run()
165         else:
166             # read config
167             f=open(storage)
168             for line in f.readlines():
169                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
170                 Module.config[key]=value                
171             f.close()
172             if options.debug:
173                 print 'Using config'
174                 for (key,message) in Module.configKeys:
175                     print key,'=',Module.config[key]
176
177     def init_moddir (self):
178         if self.options.verbose:
179             print 'Checking for',self.moddir
180         if not os.path.isdir (self.moddir):
181             self.run_fatal("svn up -N %s"%self.moddir)
182         if not os.path.isdir (self.moddir):
183             print 'Cannot find %s - check module name'%self.moddir
184             sys.exit(1)
185
186     def init_trunkdir (self):
187         if self.options.verbose:
188             print 'Checking for',self.trunkdir
189         if not os.path.isdir (self.trunkdir):
190             self.run_fatal("svn up -N %s"%self.trunkdir)
191
192     def revert_trunkdir (self):
193         if self.options.verbose:
194             print 'Checking whether',self.trunkdir,'needs being reverted'
195         if Svnpath(self.trunkdir,self.options).dir_needs_revert():
196             self.run_fatal("svn revert -R %s"%self.trunkdir)
197
198     def update_trunkdir (self):
199         if self.options.fast_checks:
200             return
201         if self.options.verbose:
202             print 'Updating',self.trunkdir
203         self.run_fatal("svn update -N %s"%self.trunkdir)
204
205     def guess_specname (self):
206         attempt="%s/%s.spec"%(self.trunkdir,self.name)
207         if os.path.isfile (attempt):
208             return attempt
209         else:
210             try:
211                 return glob("%s/*.spec"%self.trunkdir)[0]
212             except:
213                 print 'Cannot guess specfile for module %s'%self.name
214                 sys.exit(1)
215
216     def all_specnames (self):
217         return glob("%s/*.spec"%self.trunkdir)
218
219     def parse_spec (self, specfile, varnames):
220         if self.options.debug:
221             print 'parse_spec',specfile,
222         result={}
223         f=open(specfile)
224         for line in f.readlines():
225             if self.varmatcher.match(line):
226                 (var,value)=self.varmatcher.match(line).groups()
227                 if var in varnames:
228                     result[var]=value
229         f.close()
230         if self.options.verbose:
231             print 'found',len(result),'keys'
232         if self.options.debug:
233             for (k,v) in result.iteritems():
234                 print k,'=',v
235         return result
236                 
237     # stores in self.module_name_varname the rpm variable to be used for the module's name
238     # and the list of these names in self.varnames
239     def spec_dict (self):
240         specfile=self.guess_specname()
241         redirector_keys = [ varname for (varname,default) in Module.redirectors]
242         redirect_dict = self.parse_spec(specfile,redirector_keys)
243         if self.options.debug:
244             print '1st pass parsing done, redirect_dict=',redirect_dict
245         varnames=[]
246         for (varname,default) in Module.redirectors:
247             if redirect_dict.has_key(varname):
248                 setattr(self,varname,redirect_dict[varname])
249                 varnames += [redirect_dict[varname]]
250             else:
251                 setattr(self,varname,default)
252                 varnames += [ default ] 
253         self.varnames = varnames
254         result = self.parse_spec (specfile,self.varnames)
255         if self.options.debug:
256             print '2st pass parsing done, varnames=',varnames,'result=',result
257         return result
258
259     def patch_spec_var (self, patch_dict):
260         for specfile in self.all_specnames():
261             newspecfile=specfile+".new"
262             if self.options.verbose:
263                 print 'Patching',specfile,'for',patch_dict.keys()
264             spec=open (specfile)
265             new=open(newspecfile,"w")
266
267             for line in spec.readlines():
268                 if self.varmatcher.match(line):
269                     (var,value)=self.varmatcher.match(line).groups()
270                     if var in patch_dict.keys():
271                         new.write('%%define %s %s\n'%(var,patch_dict[var]))
272                         continue
273                 new.write(line)
274             spec.close()
275             new.close()
276             os.rename(newspecfile,specfile)
277
278     def unignored_lines (self, logfile):
279         result=[]
280         exclude="Tagging module %s"%self.name
281         for logline in file(logfile).readlines():
282             if logline.strip() == Module.svn_magic_line:
283                 break
284             if logline.find(exclude) < 0:
285                 result += [ logline ]
286         return result
287
288     def insert_changelog (self, logfile, oldtag, newtag):
289         for specfile in self.all_specnames():
290             newspecfile=specfile+".new"
291             if self.options.verbose:
292                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
293             spec=open (specfile)
294             new=open(newspecfile,"w")
295             for line in spec.readlines():
296                 new.write(line)
297                 if re.compile('%changelog').match(line):
298                     dateformat="* %a %b %d %Y"
299                     datepart=time.strftime(dateformat)
300                     logpart="%s <%s> - %s %s"%(Module.config['username'],
301                                                  Module.config['email'],
302                                                  oldtag,newtag)
303                     new.write(datepart+" "+logpart+"\n")
304                     for logline in self.unignored_lines(logfile):
305                         new.write("- " + logline)
306                     new.write("\n")
307             spec.close()
308             new.close()
309             os.rename(newspecfile,specfile)
310             
311     def show_dict (self, spec_dict):
312         if self.options.verbose:
313             for (k,v) in spec_dict.iteritems():
314                 print k,'=',v
315
316     def trunk_url (self):
317         return "%s/%s/trunk"%(Module.config['svnpath'],self.name)
318     def tag_name (self, spec_dict):
319         return "%s-%s-%s"%(spec_dict[self.module_name_varname],
320                            spec_dict[self.module_version_varname],
321                            spec_dict[self.module_taglevel_varname])
322     def tag_url (self, spec_dict):
323         return "%s/%s/tags/%s"%(Module.config['svnpath'],self.name,self.tag_name(spec_dict))
324
325     # locate specfile, parse it, check it and show values
326     def do_version (self):
327         self.init_moddir()
328         self.init_trunkdir()
329         self.revert_trunkdir()
330         self.update_trunkdir()
331         print '==============================',self.name
332         #for (key,message) in Module.configKeys:
333         #    print key,':',Module.config[key]
334         spec_dict = self.spec_dict()
335         print 'trunk url',self.trunk_url()
336         print 'latest tag url',self.tag_url(spec_dict)
337         print 'main specfile:',self.guess_specname()
338         print 'specfiles:',self.all_specnames()
339         for varname in self.varnames:
340             if not spec_dict.has_key(varname):
341                 print 'Could not find %%define for %s'%varname
342                 return
343             else:
344                 print varname+":",spec_dict[varname]
345
346     init_warning="""WARNING
347 The module-init function has the following limitations
348 * it does not handle changelogs
349 * it does not scan the -tags*.mk files to adopt the new tags"""
350     def do_init(self):
351         if self.options.verbose:
352             print Module.init_warning
353             if not prompt('Want to proceed anyway'):
354                 return
355
356         self.init_moddir()
357         self.init_trunkdir()
358         self.revert_trunkdir()
359         self.update_trunkdir()
360         spec_dict = self.spec_dict()
361
362         trunk_url=self.trunk_url()
363         tag_name=self.tag_name(spec_dict)
364         tag_url=self.tag_url(spec_dict)
365         # check the tag does not exist yet
366         if not self.options.fast_checks and Svnpath(tag_url,self.options).url_exists():
367             print 'Module %s already has a tag %s'%(self.name,tag_name)
368             return
369
370         if self.options.message:
371             svnopt='--message "%s"'%self.options.message
372         else:
373             svnopt='--editor-cmd=%s'%self.options.editor
374         self.run_prompt("Create initial tag",
375                         "svn copy %s %s %s"%(svnopt,trunk_url,tag_url))
376
377     def do_diff (self):
378         self.init_moddir()
379         self.init_trunkdir()
380         self.revert_trunkdir()
381         self.update_trunkdir()
382         spec_dict = self.spec_dict()
383         self.show_dict(spec_dict)
384
385         trunk_url=self.trunk_url()
386         tag_url=self.tag_url(spec_dict)
387         diff_output = Command("svn diff %s %s"%(tag_url,trunk_url),self.options).output_of()
388         if self.options.list:
389             if diff_output:
390                 print self.name
391         else:
392             if not self.options.only or diff_output:
393                 print 'x'*40,'module',self.name
394                 print 'x'*20,'<',tag_url
395                 print 'x'*20,'>',trunk_url
396                 print diff_output
397
398     def patch_tags_file (self, tagsfile, oldname, newname):
399         newtagsfile=tagsfile+".new"
400         if self.options.verbose:
401             print 'Replacing %s into %s in %s'%(oldname,newname,tagsfile)
402         tags=open (tagsfile)
403         new=open(newtagsfile,"w")
404         matcher=re.compile("^(.*)%s(.*)"%oldname)
405         for line in tags.readlines():
406             if not matcher.match(line):
407                 new.write(line)
408             else:
409                 (begin,end)=matcher.match(line).groups()
410                 new.write(begin+newname+end+"\n")
411         tags.close()
412         new.close()
413         os.rename(newtagsfile,tagsfile)
414
415     def do_tag (self):
416         self.init_moddir()
417         self.init_trunkdir()
418         self.revert_trunkdir()
419         self.update_trunkdir()
420         # parse specfile
421         spec_dict = self.spec_dict()
422         self.show_dict(spec_dict)
423         
424         # side effects
425         trunk_url=self.trunk_url()
426         old_tag_name = self.tag_name(spec_dict)
427         old_tag_url=self.tag_url(spec_dict)
428         if (self.options.new_version):
429             # new version set on command line
430             spec_dict[self.module_version_varname] = self.options.new_version
431             spec_dict[self.module_taglevel_varname] = 0
432         else:
433             # increment taglevel
434             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
435             spec_dict[self.module_taglevel_varname] = new_taglevel
436
437         # sanity check
438         new_tag_name = self.tag_name(spec_dict)
439         new_tag_url=self.tag_url(spec_dict)
440         for url in [ trunk_url, old_tag_url ] :
441             if not self.options.fast_checks and not Svnpath(url,self.options).url_exists():
442                 print 'Could not find svn URL %s'%url
443                 sys.exit(1)
444         if not self.options.fast_checks and Svnpath(new_tag_url,self.options).url_exists():
445             print 'New tag\'s svn URL %s already exists ! '%url
446             sys.exit(1)
447
448         # checking for diffs
449         diff_output=Command("svn diff %s %s"%(old_tag_url,trunk_url),
450                             self.options).output_of()
451         if len(diff_output) == 0:
452             if not prompt ("No difference in trunk for module %s, want to tag anyway"%self.name,False):
453                 return
454
455         # side effect in trunk's specfile
456         self.patch_spec_var(spec_dict)
457
458         # prepare changelog file 
459         # we use the standard subversion magic string (see svn_magic_line)
460         # so we can provide useful information, such as version numbers and diff
461         # in the same file
462         changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
463         file(changelog,"w").write("""Tagging module %s - %s
464
465 %s
466 Please write a changelog for this new tag in the section above
467 """%(self.name,new_tag_name,Module.svn_magic_line))
468
469         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
470             file(changelog,"a").write('DIFF=========\n' + diff_output)
471         
472         if self.options.debug:
473             prompt('Proceed ?')
474
475         # edit it        
476         self.run("%s %s"%(self.options.editor,changelog))
477         # insert changelog in spec
478         if self.options.changelog:
479             self.insert_changelog (changelog,old_tag_name,new_tag_name)
480
481         ## update build
482         try:
483             buildname=Module.config['build']
484         except:
485             buildname="build"
486         build = Module(buildname,self.options)
487         build.init_moddir()
488         build.init_trunkdir()
489         build.revert_trunkdir()
490         build.update_trunkdir()
491         
492         for tagsfile in glob(build.trunkdir+"/*-tags*.mk"):
493             if prompt("Want to adopt new tag in %s"%tagsfile):
494                 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name)
495
496         paths=""
497         paths += self.trunkdir + " "
498         paths += build.trunkdir + " "
499         self.run_prompt("Check","svn diff " + paths)
500         self.run_prompt("Commit","svn commit --file %s %s"%(changelog,paths))
501         self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,trunk_url,new_tag_url))
502
503         if self.options.debug:
504             print 'Preserving',changelog
505         else:
506             os.unlink(changelog)
507             
508 usage="""Usage: %prog options module1 [ .. modulen ]
509 Purpose:
510   manage subversion tags and specfile
511   requires the specfile to define name, version and taglevel
512   OR alternatively redirection variables like module_version_varname
513 """
514 functions={ 
515     'diff' : "show difference between trunk and latest tag",
516     'tag'  : """increment taglevel in specfile, insert changelog in specfile,
517                 create new tag and and adopt it in build/*-tags*.mk""",
518     'init' : "create initial tag",
519     'version' : "only check specfile and print out details"}
520
521 def main():
522
523     if sys.argv[0].find("diff") >= 0:
524         mode = "diff"
525     elif sys.argv[0].find("tag") >= 0:
526         mode = "tag"
527     elif sys.argv[0].find("init") >= 0:
528         mode = "init"
529     elif sys.argv[0].find("version") >= 0:
530         mode = "version"
531     else:
532         print "Unsupported command",sys.argv[0]
533         sys.exit(1)
534
535     global usage
536     usage += "module-%s.py : %s"%(mode,functions[mode])
537     all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
538
539     parser=OptionParser(usage=usage,version=subversion_id)
540     parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
541                       help="run on all modules as found in %s"%all_modules)
542     parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
543                       help="skip safety checks, such as svn updates -- use with care")
544     if mode == "tag" :
545         parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
546                           help="set new version and reset taglevel to 0")
547     if mode == "tag" :
548         parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
549                           help="do not update changelog section in specfile when tagging")
550     if mode == "tag" or mode == "init" :
551         parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
552                           help="specify editor")
553     if mode == "init" :
554         parser.add_option("-m","--message", action="store", dest="message", default=None,
555                           help="specify log message")
556     if mode == "diff" :
557         parser.add_option("-o","--only", action="store_true", dest="only", default=False,
558                           help="report diff only for modules that exhibit differences")
559     if mode == "diff" :
560         parser.add_option("-l","--list", action="store_true", dest="list", default=False,
561                           help="just list modules that exhibit differences")
562     parser.add_option("-w","--workdir", action="store", dest="workdir", 
563                       default="%s/%s"%(os.getenv("HOME"),"modules"),
564                       help="name for workdir - defaults to ~/modules")
565     parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
566                       help="run in verbose mode")
567     parser.add_option("-d","--debug", action="store_true", dest="debug", default=False, 
568                       help="debug mode - mostly more verbose")
569     (options, args) = parser.parse_args()
570     if options.debug: options.verbose=True
571
572     if len(args) == 0:
573         if options.all_modules:
574             args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
575         else:
576             parser.print_help()
577             sys.exit(1)
578     Module.init_homedir(options)
579     for modname in args:
580         module=Module(modname,options)
581         if sys.argv[0].find("diff") >= 0:
582             module.do_diff()
583         elif sys.argv[0].find("tag") >= 0:
584             module.do_tag()
585         elif sys.argv[0].find("init") >= 0:
586             module.do_init()
587         elif sys.argv[0].find("version") >= 0:
588             module.do_version()
589         else:
590             print "Unsupported command",sys.argv[0]
591             parser.print_help()
592             sys.exit(1)
593
594 # basically, we exit if anything goes wrong
595 if __name__ == "__main__" :
596     main()