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