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