1c2ec66f28510708220b8c2685919bbef5179118
[build.git] / module-tools.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 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase 
12 def prompt (question,default=True,other_choices=[],allow_outside=False):
13     if not isinstance (other_choices,list):
14         other_choices = [ other_choices ]
15     chars = [ c for (c,rest) in other_choices ]
16
17     choices = []
18     if 'y' not in chars:
19         if default is True: choices.append('[y]')
20         else : choices.append('y')
21     if 'n' not in chars:
22         if default is False: choices.append('[n]')
23         else : choices.append('n')
24
25     for (char,choice) in other_choices:
26         if default == char:
27             choices.append("["+char+"]"+choice)
28         else:
29             choices.append("<"+char+">"+choice)
30     try:
31         answer=raw_input(question + " " + "/".join(choices) + " ? ")
32         if not answer:
33             return default
34         answer=answer[0].lower()
35         if answer == 'y':
36             if 'y' in chars: return 'y'
37             else: return True
38         elif answer == 'n':
39             if 'n' in chars: return 'n'
40             else: return False
41         elif other_choices:
42             for (char,choice) in other_choices:
43                 if answer == char:
44                     return char
45             if allow_outside:
46                 return answer
47         return prompt(question,default,other_choices)
48     except:
49         raise
50
51 class Command:
52     def __init__ (self,command,options):
53         self.command=command
54         self.options=options
55         self.tmp="/tmp/command-%d"%os.getpid()
56
57     def run (self):
58         if self.options.verbose and self.options.mode not in Main.silent_modes:
59             print '+',self.command
60             sys.stdout.flush()
61         return os.system(self.command)
62
63     def run_silent (self):
64         if self.options.verbose:
65             print '+',self.command,' .. ',
66             sys.stdout.flush()
67         retcod=os.system(self.command + " &> " + self.tmp)
68         if retcod != 0:
69             print "FAILED ! -- output quoted below "
70             os.system("cat " + self.tmp)
71             print "FAILED ! -- end of quoted output"
72         elif self.options.verbose:
73             print "OK"
74         os.unlink(self.tmp)
75         return retcod
76
77     def run_fatal(self):
78         if self.run_silent() !=0:
79             raise Exception,"Command %s failed"%self.command
80
81     # returns stdout, like bash's $(mycommand)
82     def output_of (self,with_stderr=False):
83         tmp="/tmp/status-%d"%os.getpid()
84         if self.options.debug:
85             print '+',self.command,' .. ',
86             sys.stdout.flush()
87         command=self.command
88         if with_stderr:
89             command += " &> "
90         else:
91             command += " > "
92         command += tmp
93         os.system(command)
94         result=file(tmp).read()
95         os.unlink(tmp)
96         if self.options.debug:
97             print 'Done',
98         return result
99
100 class Svnpath:
101     def __init__(self,path,options):
102         self.path=path
103         self.options=options
104
105     def url_exists (self):
106         return os.system("svn list %s &> /dev/null"%self.path) == 0
107
108     def dir_needs_revert (self):
109         command="svn status %s"%self.path
110         return len(Command(command,self.options).output_of(True)) != 0
111     # turns out it's the same implem.
112     def file_needs_commit (self):
113         command="svn status %s"%self.path
114         return len(Command(command,self.options).output_of(True)) != 0
115
116 class Module:
117
118     svn_magic_line="--This line, and those below, will be ignored--"
119     
120     redirectors=[ # ('module_name_varname','name'),
121                   ('module_version_varname','version'),
122                   ('module_taglevel_varname','taglevel'), ]
123
124     # where to store user's config
125     config_storage="CONFIG"
126     # 
127     config={}
128
129     import commands
130     configKeys=[ ('svnpath',"Enter your toplevel svnpath",
131                   "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
132                  ("build", "Enter the name of your build module","build"),
133                  ('username',"Enter your firstname and lastname for changelogs",""),
134                  ("email","Enter your email address for changelogs",""),
135                  ]
136
137     @staticmethod
138     def prompt_config ():
139         for (key,message,default) in Module.configKeys:
140             Module.config[key]=""
141             while not Module.config[key]:
142                 Module.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
143
144
145     # for parsing module spec name:branch
146     matcher_branch_spec=re.compile("\A(?P<name>[\w-]+):(?P<branch>[\w\.]+)\Z")
147     matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
148
149     def __init__ (self,module_spec,options):
150         # parse module spec
151         attempt=Module.matcher_branch_spec.match(module_spec)
152         if attempt:
153             self.name=attempt.group('name')
154             self.branch=attempt.group('branch')
155         else:
156             self.name=module_spec
157             self.branch=None
158
159         self.options=options
160         self.moddir="%s/%s"%(options.workdir,self.name)
161
162     def friendly_name (self):
163         if not self.branch:
164             return self.name
165         else:
166             return "%s:%s"%(self.name,self.branch)
167
168     def edge_dir (self):
169         if not self.branch:
170             return "%s/trunk"%(self.moddir)
171         else:
172             return "%s/branches/%s"%(self.moddir,self.branch)
173
174     def tags_dir (self):
175         return "%s/tags"%(self.moddir)
176
177     def run (self,command):
178         return Command(command,self.options).run()
179     def run_fatal (self,command):
180         return Command(command,self.options).run_fatal()
181     def run_prompt (self,message,command):
182         if not self.options.verbose:
183             while True:
184                 choice=prompt(message,True,('s','how'))
185                 if choice is True:
186                     self.run(command)
187                     return
188                 elif choice is False:
189                     return
190                 else:
191                     print 'About to run:',command
192         else:
193             question=message+" - want to run " + command
194             if prompt(question,True):
195                 self.run(command)            
196
197     @staticmethod
198     def init_homedir (options):
199         topdir=options.workdir
200         if options.verbose and options.mode not in Main.silent_modes:
201             print 'Checking for',topdir
202         storage="%s/%s"%(topdir,Module.config_storage)
203         # sanity check. Either the topdir exists AND we have a config/storage
204         # or topdir does not exist and we create it
205         # to avoid people use their own daily svn repo
206         if os.path.isdir(topdir) and not os.path.isfile(storage):
207             print """The directory %s exists and has no CONFIG file
208 If this is your regular working directory, please provide another one as the
209 module-* commands need a fresh working dir. Make sure that you do not use 
210 that for other purposes than tagging"""%topdir
211             sys.exit(1)
212         if not os.path.isdir (topdir):
213             print "Cannot find",topdir,"let's create it"
214             Module.prompt_config()
215             print "Checking ...",
216             Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
217             Command("svn co -N %s/%s %s/%s"%(Module.config['svnpath'],
218                                              Module.config['build'],
219                                              topdir,
220                                              Module.config['build']),options).run_fatal()
221             print "OK"
222             
223             # store config
224             f=file(storage,"w")
225             for (key,message,default) in Module.configKeys:
226                 f.write("%s=%s\n"%(key,Module.config[key]))
227             f.close()
228             if options.debug:
229                 print 'Stored',storage
230                 Command("cat %s"%storage,options).run()
231         else:
232             # read config
233             f=open(storage)
234             for line in f.readlines():
235                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
236                 Module.config[key]=value                
237             f.close()
238         if options.verbose and options.mode not in Main.silent_modes:
239             print '******** Using config'
240             for (key,message,default) in Module.configKeys:
241                 print '\t',key,'=',Module.config[key]
242
243     def init_moddir (self):
244         if self.options.verbose:
245             print 'Checking for',self.moddir
246         if not os.path.isdir (self.moddir):
247             self.run_fatal("svn up -N %s"%self.moddir)
248         if not os.path.isdir (self.moddir):
249             raise Exception, 'Cannot find %s - check module name'%self.moddir
250
251     def init_subdir (self,fullpath):
252         if self.options.verbose:
253             print 'Checking for',fullpath
254         if not os.path.isdir (fullpath):
255             self.run_fatal("svn up -N %s"%fullpath)
256
257     def revert_subdir (self,fullpath):
258         if self.options.fast_checks:
259             if self.options.verbose: print 'Skipping revert of %s'%fullpath
260             return
261         if self.options.verbose:
262             print 'Checking whether',fullpath,'needs being reverted'
263         if Svnpath(fullpath,self.options).dir_needs_revert():
264             self.run_fatal("svn revert -R %s"%fullpath)
265
266     def update_subdir (self,fullpath):
267         if self.options.fast_checks:
268             if self.options.verbose: print 'Skipping update of %s'%fullpath
269             return
270         if self.options.verbose:
271             print 'Updating',fullpath
272         self.run_fatal("svn update -N %s"%fullpath)
273
274     def init_edge_dir (self):
275         # if branch, edge_dir is two steps down
276         if self.branch:
277             self.init_subdir("%s/branches"%self.moddir)
278         self.init_subdir(self.edge_dir())
279
280     def revert_edge_dir (self):
281         self.revert_subdir(self.edge_dir())
282
283     def update_edge_dir (self):
284         self.update_subdir(self.edge_dir())
285
286     def main_specname (self):
287         attempt="%s/%s.spec"%(self.edge_dir(),self.name)
288         if os.path.isfile (attempt):
289             return attempt
290         else:
291             try:
292                 return glob("%s/*.spec"%self.edge_dir())[0]
293             except:
294                 raise Exception, 'Cannot guess specfile for module %s'%self.name
295
296     def all_specnames (self):
297         return glob("%s/*.spec"%self.edge_dir())
298
299     def parse_spec (self, specfile, varnames):
300         if self.options.verbose:
301             print 'Parsing',specfile,
302             for var in varnames:
303                 print "[%s]"%var,
304             print ""
305         result={}
306         f=open(specfile)
307         for line in f.readlines():
308             attempt=Module.matcher_rpm_define.match(line)
309             if attempt:
310                 (define,var,value)=attempt.groups()
311                 if var in varnames:
312                     result[var]=value
313         f.close()
314         if self.options.debug:
315             print 'found',len(result),'keys'
316             for (k,v) in result.iteritems():
317                 print k,'=',v
318         return result
319                 
320     # stores in self.module_name_varname the rpm variable to be used for the module's name
321     # and the list of these names in self.varnames
322     def spec_dict (self):
323         specfile=self.main_specname()
324         redirector_keys = [ varname for (varname,default) in Module.redirectors]
325         redirect_dict = self.parse_spec(specfile,redirector_keys)
326         if self.options.debug:
327             print '1st pass parsing done, redirect_dict=',redirect_dict
328         varnames=[]
329         for (varname,default) in Module.redirectors:
330             if redirect_dict.has_key(varname):
331                 setattr(self,varname,redirect_dict[varname])
332                 varnames += [redirect_dict[varname]]
333             else:
334                 setattr(self,varname,default)
335                 varnames += [ default ] 
336         self.varnames = varnames
337         result = self.parse_spec (specfile,self.varnames)
338         if self.options.debug:
339             print '2st pass parsing done, varnames=',varnames,'result=',result
340         return result
341
342     def patch_spec_var (self, patch_dict,define_missing=False):
343         for specfile in self.all_specnames():
344             # record the keys that were changed
345             changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
346             newspecfile=specfile+".new"
347             if self.options.verbose:
348                 print 'Patching',specfile,'for',patch_dict.keys()
349             spec=open (specfile)
350             new=open(newspecfile,"w")
351
352             for line in spec.readlines():
353                 attempt=Module.matcher_rpm_define.match(line)
354                 if attempt:
355                     (define,var,value)=attempt.groups()
356                     if var in patch_dict.keys():
357                         if self.options.debug:
358                             print 'rewriting %s as %s'%(var,patch_dict[var])
359                         new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
360                         changed[var]=True
361                         continue
362                 new.write(line)
363             if define_missing:
364                 for (key,was_changed) in changed.iteritems():
365                     if not was_changed:
366                         if self.options.debug:
367                             print 'rewriting missed %s as %s'%(key,patch_dict[key])
368                         new.write('%%define %s %s\n'%(key,patch_dict[key]))
369             spec.close()
370             new.close()
371             os.rename(newspecfile,specfile)
372
373     def unignored_lines (self, logfile):
374         result=[]
375         exclude="Tagging module %s"%self.name
376         for logline in file(logfile).readlines():
377             if logline.strip() == Module.svn_magic_line:
378                 break
379             if logline.find(exclude) < 0:
380                 result += [ logline ]
381         return result
382
383     def insert_changelog (self, logfile, oldtag, newtag):
384         for specfile in self.all_specnames():
385             newspecfile=specfile+".new"
386             if self.options.verbose:
387                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
388             spec=open (specfile)
389             new=open(newspecfile,"w")
390             for line in spec.readlines():
391                 new.write(line)
392                 if re.compile('%changelog').match(line):
393                     dateformat="* %a %b %d %Y"
394                     datepart=time.strftime(dateformat)
395                     logpart="%s <%s> - %s %s"%(Module.config['username'],
396                                                  Module.config['email'],
397                                                  oldtag,newtag)
398                     new.write(datepart+" "+logpart+"\n")
399                     for logline in self.unignored_lines(logfile):
400                         new.write("- " + logline)
401                     new.write("\n")
402             spec.close()
403             new.close()
404             os.rename(newspecfile,specfile)
405             
406     def show_dict (self, spec_dict):
407         if self.options.verbose:
408             for (k,v) in spec_dict.iteritems():
409                 print k,'=',v
410
411     def mod_url (self):
412         return "%s/%s"%(Module.config['svnpath'],self.name)
413
414     def edge_url (self):
415         if not self.branch:
416             return "%s/trunk"%(self.mod_url())
417         else:
418             return "%s/branches/%s"%(self.mod_url(),self.branch)
419
420     def tag_name (self, spec_dict):
421         try:
422             return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
423                 self.name,
424                 spec_dict[self.module_version_varname],
425                 spec_dict[self.module_taglevel_varname])
426         except KeyError,err:
427             raise Exception, 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
428
429     def tag_url (self, spec_dict):
430         return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
431
432     def check_svnpath_exists (self, url, message):
433         if self.options.fast_checks:
434             return
435         if self.options.verbose:
436             print 'Checking url (%s) %s'%(url,message),
437         ok=Svnpath(url,self.options).url_exists()
438         if ok:
439             if self.options.verbose: print 'exists - OK'
440         else:
441             if self.options.verbose: print 'KO'
442             raise Exception, 'Could not find %s URL %s'%(message,url)
443
444     def check_svnpath_not_exists (self, url, message):
445         if self.options.fast_checks:
446             return
447         if self.options.verbose:
448             print 'Checking url (%s) %s'%(url,message),
449         ok=not Svnpath(url,self.options).url_exists()
450         if ok:
451             if self.options.verbose: print 'does not exist - OK'
452         else:
453             if self.options.verbose: print 'KO'
454             raise Exception, '%s URL %s already exists - exiting'%(message,url)
455
456     # locate specfile, parse it, check it and show values
457
458 ##############################
459     def do_version (self):
460         self.init_moddir()
461         self.init_edge_dir()
462         self.revert_edge_dir()
463         self.update_edge_dir()
464         spec_dict = self.spec_dict()
465         for varname in self.varnames:
466             if not spec_dict.has_key(varname):
467                 print 'Could not find %%define for %s'%varname
468                 return
469             else:
470                 print "%-16s %s"%(varname,spec_dict[varname])
471         if self.options.show_urls:
472             print "%-16s %s"%('edge url',self.edge_url())
473             print "%-16s %s"%('latest tag url',self.tag_url(spec_dict))
474         if self.options.verbose:
475             print "%-16s %s"%('main specfile:',self.main_specname())
476             print "%-16s %s"%('specfiles:',self.all_specnames())
477
478 ##############################
479     def do_list (self):
480 #        print 'verbose',self.options.verbose
481 #        print 'list_tags',self.options.list_tags
482 #        print 'list_branches',self.options.list_branches
483 #        print 'all_modules',self.options.all_modules
484         
485         (verbose,branches,pattern,exact) = (self.options.verbose,self.options.list_branches,
486                                             self.options.list_pattern,self.options.list_exact)
487
488         extra_command=""
489         extra_message=""
490         if self.branch:
491             pattern=self.branch
492         if pattern or exact:
493             if exact:
494                 if verbose: grep="%s/$"%exact
495                 else: grep="^%s$"%exact
496             else:
497                 grep=pattern
498             extra_command=" | grep %s"%grep
499             extra_message=" matching %s"%grep
500
501         if not branches:
502             message="==================== tags for %s"%self.friendly_name()
503             command="svn list "
504             if verbose: command+="--verbose "
505             command += "%s/tags"%self.mod_url()
506             command += extra_command
507             message += extra_message
508             if verbose: print message
509             self.run(command)
510
511         else:
512             message="==================== branches for %s"%self.friendly_name()
513             command="svn list "
514             if verbose: command+="--verbose "
515             command += "%s/branches"%self.mod_url()
516             command += extra_command
517             message += extra_message
518             if verbose: print message
519             self.run(command)
520
521 ##############################
522     sync_warning="""*** WARNING
523 The module-init function has the following limitations
524 * it does not handle changelogs
525 * it does not scan the -tags*.mk files to adopt the new tags"""
526
527     def do_sync(self):
528         if self.options.verbose:
529             print Module.sync_warning
530             if not prompt('Want to proceed anyway'):
531                 return
532
533         self.init_moddir()
534         self.init_edge_dir()
535         self.revert_edge_dir()
536         self.update_edge_dir()
537         spec_dict = self.spec_dict()
538
539         edge_url=self.edge_url()
540         tag_name=self.tag_name(spec_dict)
541         tag_url=self.tag_url(spec_dict)
542         # check the tag does not exist yet
543         self.check_svnpath_not_exists(tag_url,"new tag")
544
545         if self.options.message:
546             svnopt='--message "%s"'%self.options.message
547         else:
548             svnopt='--editor-cmd=%s'%self.options.editor
549         self.run_prompt("Create initial tag",
550                         "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
551
552 ##############################
553     def do_diff (self,compute_only=False):
554         self.init_moddir()
555         self.init_edge_dir()
556         self.revert_edge_dir()
557         self.update_edge_dir()
558         spec_dict = self.spec_dict()
559         self.show_dict(spec_dict)
560
561         edge_url=self.edge_url()
562         tag_url=self.tag_url(spec_dict)
563         self.check_svnpath_exists(edge_url,"edge track")
564         self.check_svnpath_exists(tag_url,"latest tag")
565         command="svn diff %s %s"%(tag_url,edge_url)
566         if compute_only:
567             if self.options.verbose:
568                 print 'Getting diff with %s'%command
569         diff_output = Command(command,self.options).output_of()
570         # if used as a utility
571         if compute_only:
572             return (spec_dict,edge_url,tag_url,diff_output)
573         # otherwise print the result
574         if self.options.list:
575             if diff_output:
576                 print self.name
577         else:
578             if not self.options.only or diff_output:
579                 print 'x'*30,'module',self.friendly_name()
580                 print 'x'*20,'<',tag_url
581                 print 'x'*20,'>',edge_url
582                 print diff_output
583
584 ##############################
585     # using fine_grain means replacing only those instances that currently refer to this tag
586     # otherwise, <module>-SVNPATH is replaced unconditionnally
587     def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
588         newtagsfile=tagsfile+".new"
589         tags=open (tagsfile)
590         new=open(newtagsfile,"w")
591
592         matches=0
593         # fine-grain : replace those lines that refer to oldname
594         if fine_grain:
595             if self.options.verbose:
596                 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
597             matcher=re.compile("^(.*)%s(.*)"%oldname)
598             for line in tags.readlines():
599                 if not matcher.match(line):
600                     new.write(line)
601                 else:
602                     (begin,end)=matcher.match(line).groups()
603                     new.write(begin+newname+end+"\n")
604                     matches += 1
605         # brute-force : change uncommented lines that define <module>-SVNPATH
606         else:
607             if self.options.verbose:
608                 print 'Setting %s-SVNPATH for using %s\n\tin %s .. '%(self.name,newname,tagsfile),
609             pattern="\A\s*%s-SVNPATH\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s/[^\s]+"\
610                                           %(self.name,self.name)
611             matcher_module=re.compile(pattern)
612             for line in tags.readlines():
613                 attempt=matcher_module.match(line)
614                 if attempt:
615                     svnpath="%s-SVNPATH"%self.name
616                     replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
617                     new.write(replacement)
618                     matches += 1
619                 else:
620                     new.write(line)
621         tags.close()
622         new.close()
623         os.rename(newtagsfile,tagsfile)
624         if self.options.verbose: print "%d changes"%matches
625         return matches
626
627     def do_tag (self):
628         self.init_moddir()
629         self.init_edge_dir()
630         self.revert_edge_dir()
631         self.update_edge_dir()
632         # parse specfile
633         spec_dict = self.spec_dict()
634         self.show_dict(spec_dict)
635         
636         # side effects
637         edge_url=self.edge_url()
638         old_tag_name = self.tag_name(spec_dict)
639         old_tag_url=self.tag_url(spec_dict)
640         if (self.options.new_version):
641             # new version set on command line
642             spec_dict[self.module_version_varname] = self.options.new_version
643             spec_dict[self.module_taglevel_varname] = 0
644         else:
645             # increment taglevel
646             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
647             spec_dict[self.module_taglevel_varname] = new_taglevel
648
649         # sanity check
650         new_tag_name = self.tag_name(spec_dict)
651         new_tag_url=self.tag_url(spec_dict)
652         self.check_svnpath_exists (edge_url,"edge track")
653         self.check_svnpath_exists (old_tag_url,"previous tag")
654         self.check_svnpath_not_exists (new_tag_url,"new tag")
655
656         # checking for diffs
657         diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
658                             self.options).output_of()
659         if len(diff_output) == 0:
660             if not prompt ("No difference in trunk for module %s, want to tag anyway"%self.name,False):
661                 return
662
663         # side effect in trunk's specfile
664         self.patch_spec_var(spec_dict)
665
666         # prepare changelog file 
667         # we use the standard subversion magic string (see svn_magic_line)
668         # so we can provide useful information, such as version numbers and diff
669         # in the same file
670         changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
671         file(changelog,"w").write("""Tagging module %s - %s
672
673 %s
674 Please write a changelog for this new tag in the section above
675 """%(self.name,new_tag_name,Module.svn_magic_line))
676
677         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
678             file(changelog,"a").write('DIFF=========\n' + diff_output)
679         
680         if self.options.debug:
681             prompt('Proceed ?')
682
683         # edit it        
684         self.run("%s %s"%(self.options.editor,changelog))
685         # insert changelog in spec
686         if self.options.changelog:
687             self.insert_changelog (changelog,old_tag_name,new_tag_name)
688
689         ## update build
690         try:
691             buildname=Module.config['build']
692         except:
693             buildname="build"
694         build = Module(buildname,self.options)
695         build.init_moddir()
696         build.init_edge_dir()
697         build.revert_edge_dir()
698         build.update_edge_dir()
699         
700         tagsfiles=glob(build.edge_dir()+"/*-tags*.mk")
701         tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
702         default_answer = 'y'
703         while True:
704             for (tagsfile,status) in tagsdict.iteritems():
705                 basename=os.path.basename(tagsfile)
706                 print ".................... Dealing with %s"%basename
707                 while tagsdict[tagsfile] == 'todo' :
708                     choice = prompt ("insert %s in %s    "%(new_tag_name,basename),default_answer,
709                                      [ ('y','es'), ('n', 'ext'), ('f','orce'), 
710                                        ('d','iff'), ('r','evert'), ('h','elp') ] ,
711                                      allow_outside=True)
712                     if choice == 'y':
713                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
714                     elif choice == 'n':
715                         print 'Done with %s'%os.path.basename(tagsfile)
716                         tagsdict[tagsfile]='done'
717                     elif choice == 'f':
718                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
719                     elif choice == 'd':
720                         self.run("svn diff %s"%tagsfile)
721                     elif choice == 'r':
722                         self.run("svn revert %s"%tagsfile)
723                     else:
724                         name=self.name
725                         print """y: change %(name)s-SVNPATH only if it currently refers to %(old_tag_name)s
726 f: unconditionnally change any line setting %(name)s-SVNPATH to using %(new_tag_name)s
727 d: show current diff for this tag file
728 r: revert that tag file
729 n: move to next file"""%locals()
730
731             if prompt("Want to review changes on tags files",False):
732                 tagsdict = dict ( [ (x, 'todo') for tagsfile in tagsfiles ] )
733                 default_answer='d'
734             else:
735                 break
736
737         paths=""
738         paths += self.edge_dir() + " "
739         paths += build.edge_dir() + " "
740         self.run_prompt("Review trunk and build","svn diff " + paths)
741         self.run_prompt("Commit trunk and build","svn commit --file %s %s"%(changelog,paths))
742         self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
743
744         if self.options.debug:
745             print 'Preserving',changelog
746         else:
747             os.unlink(changelog)
748             
749 ##############################
750     def do_branch (self):
751
752         # save self.branch if any, as a hint for the new branch 
753         # do this before anything else and restore .branch to None, 
754         # as this is part of the class's logic
755         new_trunk_name=None
756         if self.branch:
757             new_trunk_name=self.branch
758             self.branch=None
759
760         # compute diff - a way to initialize the whole stuff
761         # do_diff already does edge_dir initialization
762         # and it checks that edge_url and tag_url exist as well
763         (spec_dict,edge_url,tag_url,diff_listing) = self.do_diff(compute_only=True)
764
765         # the version name in the trunk becomes the new branch name
766         branch_name = spec_dict[self.module_version_varname]
767
768         # figure new branch name (the one for the trunk) if not provided on the command line
769         if not new_trunk_name:
770             # heuristic is to assume 'version' is a dot-separated name
771             # we isolate the rightmost part and try incrementing it by 1
772             version=spec_dict[self.module_version_varname]
773             try:
774                 m=re.compile("\A(?P<leftpart>.+)\.(?P<rightmost>[^\.]+)\Z")
775                 (leftpart,rightmost)=m.match(version).groups()
776                 incremented = int(rightmost)+1
777                 new_trunk_name="%s.%d"%(leftpart,incremented)
778             except:
779                 raise Exception, 'Cannot figure next branch name from %s - exiting'%version
780
781         # record starting point tagname
782         latest_tag_name = self.tag_name(spec_dict)
783
784         print "**********"
785         print "Using starting point %s (%s)"%(tag_url,latest_tag_name)
786         print "Creating branch %s  &  moving trunk to %s"%(branch_name,new_trunk_name)
787         print "**********"
788
789         # print warning if pending diffs
790         if diff_listing:
791             print """*** WARNING : Module %s has pending diffs on its trunk
792 It is safe to proceed, but please note that branch %s
793 will be based on latest tag %s and *not* on the current trunk"""%(self.name,branch_name,latest_tag_name)
794             while True:
795                 answer = prompt ('Are you sure you want to proceed with branching',True,('d','iff'))
796                 if answer is True:
797                     break
798                 elif answer is False:
799                     raise Exception,"User quit"
800                 elif answer == 'd':
801                     print '<<<< %s'%tag_url
802                     print '>>>> %s'%edge_url
803                     print diff_listing
804
805         branch_url = "%s/%s/branches/%s"%(Module.config['svnpath'],self.name,branch_name)
806         self.check_svnpath_not_exists (branch_url,"new branch")
807         
808         # patching trunk
809         spec_dict[self.module_version_varname]=new_trunk_name
810         spec_dict[self.module_taglevel_varname]='0'
811         # remember this in the trunk for easy location of the current branch
812         spec_dict['module_current_branch']=branch_name
813         self.patch_spec_var(spec_dict,True)
814         
815         # create commit log file
816         tmp="/tmp/branching-%d"%os.getpid()
817         f=open(tmp,"w")
818         f.write("Branch %s for module %s created from tag %s\n"%(new_trunk_name,self.name,latest_tag_name))
819         f.close()
820
821         # we're done, let's commit the stuff
822         command="svn diff %s"%self.edge_dir()
823         self.run_prompt("Review changes in trunk",command)
824         command="svn copy --file %s %s %s"%(tmp,self.edge_url(),branch_url)
825         self.run_prompt("Create branch",command)
826         command="svn commit --file %s %s"%(tmp,self.edge_dir())
827         self.run_prompt("Commit trunk",command)
828         new_tag_url=self.tag_url(spec_dict)
829         command="svn copy --file %s %s %s"%(tmp,self.edge_url(),new_tag_url)
830         self.run_prompt("Create initial tag in trunk",command)
831         os.unlink(tmp)
832
833 ##############################
834 class Main:
835
836     usage="""Usage: %prog options module_desc [ .. module_desc ]
837 Purpose:
838   manage subversion tags and specfile
839   requires the specfile to define *version* and *taglevel*
840   OR alternatively 
841   redirection variables module_version_varname / module_taglevel_varname
842 Trunk:
843   by default, the trunk of modules is taken into account
844   in this case, just mention the module name as <module_desc>
845 Branches:
846   if you wish to work on a branch rather than on the trunk, 
847   you can use something like e.g. Mom:2.1 as <module_desc>
848 More help:
849   see http://svn.planet-lab.org/wiki/ModuleTools
850 """
851
852     modes={ 
853         'list' : "displays a list of available tags or branches",
854         'version' : "check latest specfile and print out details",
855         'diff' : "show difference between trunk and latest tag",
856         'tag'  : """increment taglevel in specfile, insert changelog in specfile,
857                 create new tag and and monitor its adoption in build/*-tags*.mk""",
858         'branch' : """create a branch for this module, from the latest tag on the trunk, 
859                   and change trunk's version number to reflect the new branch name;
860                   you can specify the new branch name by using module:branch""",
861         'sync' : """create a tag from the trunk
862                 this is a last resort option, mostly for repairs""",
863         }
864
865     silent_modes = ['list']
866
867     def run(self):
868
869         mode=None
870         for function in Main.modes.keys():
871             if sys.argv[0].find(function) >= 0:
872                 mode = function
873                 break
874         if not mode:
875             print "Unsupported command",sys.argv[0]
876             sys.exit(1)
877
878         Main.usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
879         all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
880
881         parser=OptionParser(usage=Main.usage,version=subversion_id)
882         
883         if mode == 'list':
884             parser.add_option("-b","--branches",action="store_true",dest="list_branches",default=False,
885                               help="list branches")
886             parser.add_option("-t","--tags",action="store_false",dest="list_branches",
887                               help="list tags")
888             parser.add_option("-m","--match",action="store",dest="list_pattern",default=None,
889                                help="grep pattern for filtering output")
890             parser.add_option("-x","--exact-match",action="store",dest="list_exact",default=None,
891                                help="exact grep pattern for filtering output")
892         if mode == "tag" or mode == 'branch':
893             parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
894                               help="set new version and reset taglevel to 0")
895         if mode == "tag" :
896             parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
897                               help="do not update changelog section in specfile when tagging")
898         if mode == "tag" or mode == "sync" :
899             parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
900                               help="specify editor")
901         if mode == "sync" :
902             parser.add_option("-m","--message", action="store", dest="message", default=None,
903                               help="specify log message")
904         if mode == "diff" :
905             parser.add_option("-o","--only", action="store_true", dest="only", default=False,
906                               help="report diff only for modules that exhibit differences")
907         if mode == "diff" :
908             parser.add_option("-l","--list", action="store_true", dest="list", default=False,
909                               help="just list modules that exhibit differences")
910
911         if mode  == 'version':
912             parser.add_option("-u","--url", action="store_true", dest="show_urls", default=False,
913                               help="display URLs")
914             
915         # default verbosity depending on function - temp
916         parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
917                           help="run on all modules as found in %s"%all_modules)
918         verbose_default=False
919         if mode in ['tag','sync'] : verbose_default = True
920         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=verbose_default, 
921                           help="run in verbose mode")
922         if mode not in ['version','list']:
923             parser.add_option("-q","--quiet", action="store_false", dest="verbose", 
924                               help="run in quiet (non-verbose) mode")
925         parser.add_option("-w","--workdir", action="store", dest="workdir", 
926                           default="%s/%s"%(os.getenv("HOME"),"modules"),
927                           help="""name for dedicated working dir - defaults to ~/modules
928 ** THIS MUST NOT ** be your usual working directory""")
929         parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
930                           help="skip safety checks, such as svn updates -- use with care")
931         parser.add_option("-d","--debug", action="store_true", dest="debug", default=False, 
932                           help="debug mode - mostly more verbose")
933         (options, args) = parser.parse_args()
934         options.mode=mode
935
936         if len(args) == 0:
937             if options.all_modules:
938                 args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
939             else:
940                 parser.print_help()
941                 sys.exit(1)
942         Module.init_homedir(options)
943         for modname in args:
944             module=Module(modname,options)
945             if len(args)>1 and mode not in Main.silent_modes:
946                 print '========================================',module.friendly_name()
947             # call the method called do_<mode>
948             method=Module.__dict__["do_%s"%mode]
949             try:
950                 method(module)
951             except Exception,e:
952                 print 'Skipping failed %s - %r'%(modname,e)
953
954 if __name__ == "__main__" :
955     try:
956         Main().run()
957     except KeyboardInterrupt:
958         print '\nBye'
959