check diffs before tagging - util-vserver not yet subject to tags
[build.git] / module-tag.py
1 #!/usr/bin/python -u
2
3 subversion_id = "$Id: TestMain.py 7635 2008-01-04 09:46:06Z thierry $"
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     config={}
108
109     svn_magic_line="--This line, and those below, will be ignored--"
110     
111     redirectors=[ ('module_name_varname','name'),
112                   ('module_version_varname','version'),
113                   ('module_taglevel_varname','taglevel'), ]
114
115     def __init__ (self,name,options):
116         self.name=name
117         self.options=options
118         self.moddir="%s/%s/%s"%(os.getenv("HOME"),options.modules,name)
119         self.trunkdir="%s/trunk"%(self.moddir)
120         self.varmatcher=re.compile("%define\s+(\S+)\s+(\S*)\s*")
121
122
123     def run (self,command):
124         return Command(command,self.options).run()
125     def run_fatal (self,command):
126         return Command(command,self.options).run_fatal()
127     def run_prompt (self,message,command):
128         if not self.options.verbose:
129             question=message
130         else:
131             question="Want to run " + command
132         if prompt(question,True):
133             self.run(command)            
134
135     @staticmethod
136     def init_homedir (options):
137         topdir="%s/%s"%(os.getenv("HOME"),options.modules)
138         if options.verbose:
139             print 'Checking for',topdir
140         storage="%s/%s"%(topdir,Module.config_storage)
141         if not os.path.isdir (topdir):
142             # prompt for login or whatever svnpath
143             print "Cannot find",topdir,"let's create it"
144             for (key,message) in Module.configKeys:
145                 Module.config[key]=raw_input(message+" : ").strip()
146             Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
147             # store config
148             f=file(storage,"w")
149             for (key,message) in Module.configKeys:
150                 f.write("%s=%s\n"%(key,Module.config[key]))
151             f.close()
152             if options.debug:
153                 print 'Stored',storage
154                 Command("cat %s"%storage,options).run()
155         else:
156             # read config
157             f=open(storage)
158             for line in f.readlines():
159                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
160                 Module.config[key]=value                
161             f.close()
162             if options.debug:
163                 print 'Using config'
164                 for (key,message) in Module.configKeys:
165                     print key,'=',Module.config[key]
166
167     def init_moddir (self):
168         if self.options.verbose:
169             print 'Checking for',self.moddir
170         if not os.path.isdir (self.moddir):
171             self.run_fatal("svn up -N %s"%self.moddir)
172         if not os.path.isdir (self.moddir):
173             print 'Cannot find %s - check module name'%self.moddir
174             sys.exit(1)
175
176     def init_trunkdir (self):
177         if self.options.verbose:
178             print 'Checking for',self.trunkdir
179         if not os.path.isdir (self.trunkdir):
180             self.run_fatal("svn up -N %s"%self.trunkdir)
181
182     def revert_trunkdir (self):
183         if self.options.verbose:
184             print 'Checking whether',self.trunkdir,'needs being reverted'
185         if Svnpath(self.trunkdir,self.options).dir_needs_revert():
186             self.run_fatal("svn revert -R %s"%self.trunkdir)
187
188     def update_trunkdir (self):
189         if self.options.skip_update:
190             return
191         if self.options.verbose:
192             print 'Updating',self.trunkdir
193         self.run_fatal("svn update %s"%self.trunkdir)
194
195     def guess_specname (self):
196         attempt="%s/%s.spec"%(self.trunkdir,self.name)
197         if os.path.isfile (attempt):
198             return attempt
199         else:
200             try:
201                 return glob("%s/*.spec"%self.trunkdir)[0]
202             except:
203                 print 'Cannot guess specfile for module %s'%self.name
204                 sys.exit(1)
205
206     def parse_spec (self, specfile, varnames):
207         if self.options.debug:
208             print 'parse_spec',specfile,
209         result={}
210         f=open(specfile)
211         for line in f.readlines():
212             if self.varmatcher.match(line):
213                 (var,value)=self.varmatcher.match(line).groups()
214                 if var in varnames:
215                     result[var]=value
216         f.close()
217         if self.options.verbose:
218             print 'found',len(result),'keys'
219         if self.options.debug:
220             for (k,v) in result.iteritems():
221                 print k,'=',v
222         return result
223                 
224     # stores in self.module_name_varname the rpm variable to be used for the module's name
225     # and the list of these names in self.varnames
226     def spec_dict (self):
227         specfile=self.guess_specname()
228         redirector_keys = [ varname for (varname,default) in Module.redirectors]
229         redirect_dict = self.parse_spec(specfile,redirector_keys)
230         if self.options.debug:
231             print '1st pass parsing done, redirect_dict=',redirect_dict
232         varnames=[]
233         for (varname,default) in Module.redirectors:
234             if redirect_dict.has_key(varname):
235                 setattr(self,varname,redirect_dict[varname])
236                 varnames += [redirect_dict[varname]]
237             else:
238                 setattr(self,varname,default)
239                 varnames += [ default ] 
240         self.varnames = varnames
241         result = self.parse_spec (specfile,self.varnames)
242         if self.options.debug:
243             print '2st pass parsing done, varnames=',varnames,'result=',result
244         return result
245
246     def patch_spec_var (self, patch_dict):
247         specfile=self.guess_specname()
248         newspecfile=specfile+".new"
249         if self.options.verbose:
250             print 'Patching',specfile,'for',patch_dict.keys()
251         spec=open (specfile)
252         new=open(newspecfile,"w")
253
254         for line in spec.readlines():
255             if self.varmatcher.match(line):
256                 (var,value)=self.varmatcher.match(line).groups()
257                 if var in patch_dict.keys():
258                     new.write('%%define %s %s\n'%(var,patch_dict[var]))
259                     continue
260             new.write(line)
261         spec.close()
262         new.close()
263         os.rename(newspecfile,specfile)
264
265     def unignored_lines (self, logfile):
266         result=[]
267         exclude="Tagging module %s"%self.name
268         for logline in file(logfile).readlines():
269             if logline.strip() == Module.svn_magic_line:
270                 break
271             if logline.find(exclude) < 0:
272                 result += [ logline ]
273         return result
274
275     def insert_changelog (self, logfile, oldtag, newtag):
276         specfile=self.guess_specname()
277         newspecfile=specfile+".new"
278         if self.options.verbose:
279             print 'Inserting changelog from %s into %s'%(logfile,specfile)
280         spec=open (specfile)
281         new=open(newspecfile,"w")
282         for line in spec.readlines():
283             new.write(line)
284             if re.compile('%changelog').match(line):
285                 dateformat="* %a %b %d %Y"
286                 datepart=time.strftime(dateformat)
287                 logpart="%s <%s> - %s %s"%(Module.config['username'],
288                                              Module.config['email'],
289                                              oldtag,newtag)
290                 new.write(datepart+" "+logpart+"\n")
291                 for logline in self.unignored_lines(logfile):
292                     new.write("- " + logline)
293                 new.write("\n")
294         spec.close()
295         new.close()
296         os.rename(newspecfile,specfile)
297             
298     def show_dict (self, spec_dict):
299         if self.options.verbose:
300             for (k,v) in spec_dict.iteritems():
301                 print k,'=',v
302
303     def trunk_url (self):
304         return "%s/%s/trunk"%(Module.config['svnpath'],self.name)
305     def tag_name (self, spec_dict):
306         return "%s-%s-%s"%(spec_dict[self.module_name_varname],
307                            spec_dict[self.module_version_varname],
308                            spec_dict[self.module_taglevel_varname])
309     def tag_url (self, spec_dict):
310         return "%s/%s/tags/%s"%(Module.config['svnpath'],self.name,self.tag_name(spec_dict))
311
312     # locate specfile, parse it, check it and show values
313     def do_version (self):
314         self.init_moddir()
315         self.init_trunkdir()
316         self.revert_trunkdir()
317         self.update_trunkdir()
318         print '==============================',self.name
319         #for (key,message) in Module.configKeys:
320         #    print key,':',Module.config[key]
321         spec_dict = self.spec_dict()
322         print 'trunk url',self.trunk_url()
323         print 'latest tag url',self.tag_url(spec_dict)
324         print 'specfile:',self.guess_specname()
325         for varname in self.varnames:
326             if not spec_dict.has_key(varname):
327                 print 'Could not find %%define for %s'%varname
328                 return
329             else:
330                 print varname+":",spec_dict[varname]
331
332     init_warning="""WARNING
333 The module-init function has the following limitations
334 * it does not handle changelogs
335 * it does not scan the -tags*.mk files to adopt the new tags"""
336     def do_init(self):
337         if self.options.verbose:
338             print Module.init_warning
339             if not prompt('Want to proceed anyway'):
340                 return
341
342         self.init_moddir()
343         self.init_trunkdir()
344         self.revert_trunkdir()
345         self.update_trunkdir()
346         spec_dict = self.spec_dict()
347
348         trunk_url=self.trunk_url()
349         tag_name=self.tag_name(spec_dict)
350         tag_url=self.tag_url(spec_dict)
351         # check the tag does not exist yet
352         if Svnpath(tag_url,self.options).url_exists():
353             print 'Module %s already has a tag %s'%(self.name,tag_name)
354             return
355
356         if self.options.message:
357             svnopt='--message "%s"'%self.options.message
358         else:
359             svnopt='--editor-cmd=%s'%self.options.editor
360         self.run_prompt("Create initial tag",
361                         "svn copy %s %s %s"%(svnopt,trunk_url,tag_url))
362
363     def do_diff (self):
364         self.init_moddir()
365         self.init_trunkdir()
366         self.revert_trunkdir()
367         self.update_trunkdir()
368         spec_dict = self.spec_dict()
369         self.show_dict(spec_dict)
370
371         trunk_url=self.trunk_url()
372         tag_url=self.tag_url(spec_dict)
373         print 'x'*67,self.name
374         self.run("svn diff %s %s"%(tag_url,trunk_url))
375
376     def patch_tags_file (self, tagsfile, oldname, newname):
377         newtagsfile=tagsfile+".new"
378         if self.options.verbose:
379             print 'Replacing %s into %s in %s'%(oldname,newname,tagsfile)
380         tags=open (tagsfile)
381         new=open(newtagsfile,"w")
382         matcher=re.compile("^(.*)%s(.*)"%oldname)
383         for line in tags.readlines():
384             if not matcher.match(line):
385                 new.write(line)
386             else:
387                 (begin,end)=matcher.match(line).groups()
388                 new.write(begin+newname+end+"\n")
389         tags.close()
390         new.close()
391         os.rename(newtagsfile,tagsfile)
392
393     def do_tag (self):
394         self.init_moddir()
395         self.init_trunkdir()
396         self.revert_trunkdir()
397         self.update_trunkdir()
398         # parse specfile
399         spec_dict = self.spec_dict()
400         self.show_dict(spec_dict)
401         
402         # side effects
403         trunk_url=self.trunk_url()
404         old_tag_name = self.tag_name(spec_dict)
405         old_tag_url=self.tag_url(spec_dict)
406         if (self.options.new_version):
407             # new version set on command line
408             spec_dict[self.module_version_varname] = self.options.new_version
409             spec_dict[self.module_taglevel_varname] = 0
410         else:
411             # increment taglevel
412             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
413             spec_dict[self.module_taglevel_varname] = new_taglevel
414
415         # sanity check
416         new_tag_name = self.tag_name(spec_dict)
417         new_tag_url=self.tag_url(spec_dict)
418         for url in [ trunk_url, old_tag_url ] :
419             if not Svnpath(url,self.options).url_exists():
420                 print 'Could not find svn URL %s'%url
421                 sys.exit(1)
422         if Svnpath(new_tag_url,self.options).url_exists():
423             print 'New tag\'s svn URL %s already exists ! '%url
424             sys.exit(1)
425
426         # checking for diffs
427         diff_output=Command("svn diff %s %s"%(old_tag_url,trunk_url),
428                             self.options).output_of()
429         if len(diff_output) == 0:
430             if not prompt ("No difference in trunk for module %s, want to tag anyway"%self.name,False):
431                 return
432
433         # side effect in trunk's specfile
434         self.patch_spec_var(spec_dict)
435
436         # prepare changelog file 
437         # we use the standard subversion magic string (see svn_magic_line)
438         # so we can provide useful information, such as version numbers and diff
439         # in the same file
440         changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
441         file(changelog,"w").write("""Tagging module %s  -- from %s to %s
442
443 %s
444 Please write a changelog for this new tag in the section above
445 """%(self.name,old_tag_name,new_tag_name,Module.svn_magic_line))
446
447         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
448             file(changelog,"w").write('DIFF=========\n' + diff_output)
449         
450         if self.options.debug:
451             prompt('Proceed ?')
452
453         # edit it        
454         self.run("%s %s"%(self.options.editor,changelog))
455         # insert changelog in spec
456         if self.options.changelog:
457             self.insert_changelog (changelog,old_tag_name,new_tag_name)
458
459         ## update build
460         build = Module(self.options.build,self.options)
461         build.init_moddir()
462         build.init_trunkdir()
463         build.revert_trunkdir()
464         build.update_trunkdir()
465         
466         for tagsfile in glob(build.trunkdir+"/*-tags*.mk"):
467             if prompt("Want to adopt new tag in %s"%tagsfile):
468                 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name)
469
470         paths=""
471         paths += self.trunkdir + " "
472         paths += build.trunkdir + " "
473         self.run_prompt("Check","svn diff " + paths)
474         self.run_prompt("Commit","svn commit --file %s %s"%(changelog,paths))
475         self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,trunk_url,new_tag_url))
476
477         if self.options.debug:
478             print 'Preserving',changelog
479         else:
480             os.unlink(changelog)
481             
482 usage="""Usage: %prog options module1 [ .. modulen ]
483 Purpose:
484   manage subversion tags and specfile
485   requires the specfile to define name, version and taglevel
486   OR alternatively redirection variables like module_version_varname
487 Available functions:
488   module-diff : show difference between trunk and latest tag
489   module-tag  : increment taglevel in specfile, insert changelog in specfile,
490                 create new tag and and adopt it in build/*-tags*.mk
491   module-init : create initial tag
492   module-version : only check specfile and print out details"""
493
494 def main():
495     all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
496
497     parser=OptionParser(usage=usage,version=subversion_id)
498     parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
499                       help="When tagging, set new version and reset taglevel to 0")
500     parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
501                       help="Runs all modules as found in %s"%all_modules)
502     parser.add_option("-u","--no-update",action="store_true",dest="skip_update",default=False,
503                       help="Skips svn updates")
504     parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
505                       help="Does not update changelog section in specfile when tagging")
506     parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
507                       help="Specify editor")
508     parser.add_option("-m","--message", action="store", dest="message", default=None,
509                       help="Specify log message")
510     parser.add_option("-M","--modules", action="store", dest="modules", default="modules",
511                       help="Name for topdir - defaults to modules")
512     parser.add_option("-B","--build", action="store", dest="build", default="build",
513                       help="Set module name for build, defaults to build")
514     parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
515                       help="Run in verbose mode")
516     parser.add_option("-d","--debug", action="store_true", dest="debug", default=False, 
517                       help="Debug mode - mostly more verbose")
518     (options, args) = parser.parse_args()
519     if options.debug: options.verbose=True
520
521     if len(args) == 0:
522         if options.all_modules:
523             args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
524         else:
525             parser.print_help()
526             sys.exit(1)
527     Module.init_homedir(options)
528     for modname in args:
529         module=Module(modname,options)
530         if sys.argv[0].find("diff") >= 0:
531             module.do_diff()
532         elif sys.argv[0].find("tag") >= 0:
533             module.do_tag()
534         elif sys.argv[0].find("init") >= 0:
535             module.do_init()
536         elif sys.argv[0].find("version") >= 0:
537             module.do_version()
538         else:
539             print "Unsupported command",sys.argv[0]
540             parser.print_help()
541             sys.exit(1)
542
543 # basically, we exit if anything goes wrong
544 if __name__ == "__main__" :
545     main()