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