b7d60eaf827040c79409ba3899069a777620fd3a
[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         white_line_matcher = re.compile("\A\s*\Z")
384         for logline in file(logfile).readlines():
385             if logline.strip() == Module.svn_magic_line:
386                 break
387             if logline.find(exclude) >= 0:
388                 continue
389             elif white_line_matcher.match(logline):
390                 continue
391             else:
392                 result.append(logline.strip()+'\n')
393         return result
394
395     def insert_changelog (self, logfile, oldtag, newtag):
396         for specfile in self.all_specnames():
397             newspecfile=specfile+".new"
398             if self.options.verbose:
399                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
400             spec=open (specfile)
401             new=open(newspecfile,"w")
402             for line in spec.readlines():
403                 new.write(line)
404                 if re.compile('%changelog').match(line):
405                     dateformat="* %a %b %d %Y"
406                     datepart=time.strftime(dateformat)
407                     logpart="%s <%s> - %s"%(Module.config['username'],
408                                                  Module.config['email'],
409                                                  newtag)
410                     new.write(datepart+" "+logpart+"\n")
411                     for logline in self.unignored_lines(logfile):
412                         new.write("- " + logline)
413                     new.write("\n")
414             spec.close()
415             new.close()
416             os.rename(newspecfile,specfile)
417             
418     def show_dict (self, spec_dict):
419         if self.options.verbose:
420             for (k,v) in spec_dict.iteritems():
421                 print k,'=',v
422
423     def mod_url (self):
424         return "%s/%s"%(Module.config['svnpath'],self.name)
425
426     def edge_url (self):
427         if not self.branch:
428             return "%s/trunk"%(self.mod_url())
429         else:
430             return "%s/branches/%s"%(self.mod_url(),self.branch)
431
432     def tag_name (self, spec_dict):
433         try:
434             return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
435                 self.name,
436                 spec_dict[self.module_version_varname],
437                 spec_dict[self.module_taglevel_varname])
438         except KeyError,err:
439             raise Exception, 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
440
441     def tag_url (self, spec_dict):
442         return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
443
444     def check_svnpath_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=Svnpath(url,self.options).url_exists()
450         if ok:
451             if self.options.verbose: print 'exists - OK'
452         else:
453             if self.options.verbose: print 'KO'
454             raise Exception, 'Could not find %s URL %s'%(message,url)
455
456     def check_svnpath_not_exists (self, url, message):
457         if self.options.fast_checks:
458             return
459         if self.options.verbose:
460             print 'Checking url (%s) %s'%(url,message),
461         ok=not Svnpath(url,self.options).url_exists()
462         if ok:
463             if self.options.verbose: print 'does not exist - OK'
464         else:
465             if self.options.verbose: print 'KO'
466             raise Exception, '%s URL %s already exists - exiting'%(message,url)
467
468     # locate specfile, parse it, check it and show values
469
470 ##############################
471     def do_version (self):
472         self.init_moddir()
473         self.init_edge_dir()
474         self.revert_edge_dir()
475         self.update_edge_dir()
476         spec_dict = self.spec_dict()
477         for varname in self.varnames:
478             if not spec_dict.has_key(varname):
479                 print 'Could not find %%define for %s'%varname
480                 return
481             else:
482                 print "%-16s %s"%(varname,spec_dict[varname])
483         if self.options.show_urls:
484             print "%-16s %s"%('edge url',self.edge_url())
485             print "%-16s %s"%('latest tag url',self.tag_url(spec_dict))
486         if self.options.verbose:
487             print "%-16s %s"%('main specfile:',self.main_specname())
488             print "%-16s %s"%('specfiles:',self.all_specnames())
489
490 ##############################
491     def do_list (self):
492 #        print 'verbose',self.options.verbose
493 #        print 'list_tags',self.options.list_tags
494 #        print 'list_branches',self.options.list_branches
495 #        print 'all_modules',self.options.all_modules
496         
497         (verbose,branches,pattern,exact) = (self.options.verbose,self.options.list_branches,
498                                             self.options.list_pattern,self.options.list_exact)
499
500         extra_command=""
501         extra_message=""
502         if self.branch:
503             pattern=self.branch
504         if pattern or exact:
505             if exact:
506                 if verbose: grep="%s/$"%exact
507                 else: grep="^%s$"%exact
508             else:
509                 grep=pattern
510             extra_command=" | grep %s"%grep
511             extra_message=" matching %s"%grep
512
513         if not branches:
514             message="==================== tags for %s"%self.friendly_name()
515             command="svn list "
516             if verbose: command+="--verbose "
517             command += "%s/tags"%self.mod_url()
518             command += extra_command
519             message += extra_message
520             if verbose: print message
521             self.run(command)
522
523         else:
524             message="==================== branches for %s"%self.friendly_name()
525             command="svn list "
526             if verbose: command+="--verbose "
527             command += "%s/branches"%self.mod_url()
528             command += extra_command
529             message += extra_message
530             if verbose: print message
531             self.run(command)
532
533 ##############################
534     sync_warning="""*** WARNING
535 The module-sync function has the following limitations
536 * it does not handle changelogs
537 * it does not scan the -tags*.mk files to adopt the new tags"""
538
539     def do_sync(self):
540         if self.options.verbose:
541             print Module.sync_warning
542             if not prompt('Want to proceed anyway'):
543                 return
544
545         self.init_moddir()
546         self.init_edge_dir()
547         self.revert_edge_dir()
548         self.update_edge_dir()
549         spec_dict = self.spec_dict()
550
551         edge_url=self.edge_url()
552         tag_name=self.tag_name(spec_dict)
553         tag_url=self.tag_url(spec_dict)
554         # check the tag does not exist yet
555         self.check_svnpath_not_exists(tag_url,"new tag")
556
557         if self.options.message:
558             svnopt='--message "%s"'%self.options.message
559         else:
560             svnopt='--editor-cmd=%s'%self.options.editor
561         self.run_prompt("Create initial tag",
562                         "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
563
564 ##############################
565     def do_diff (self,compute_only=False):
566         self.init_moddir()
567         self.init_edge_dir()
568         self.revert_edge_dir()
569         self.update_edge_dir()
570         spec_dict = self.spec_dict()
571         self.show_dict(spec_dict)
572
573         edge_url=self.edge_url()
574         tag_url=self.tag_url(spec_dict)
575         self.check_svnpath_exists(edge_url,"edge track")
576         self.check_svnpath_exists(tag_url,"latest tag")
577         command="svn diff %s %s"%(tag_url,edge_url)
578         if compute_only:
579             if self.options.verbose:
580                 print 'Getting diff with %s'%command
581         diff_output = Command(command,self.options).output_of()
582         # if used as a utility
583         if compute_only:
584             return (spec_dict,edge_url,tag_url,diff_output)
585         # otherwise print the result
586         if self.options.list:
587             if diff_output:
588                 print self.name
589         else:
590             if not self.options.only or diff_output:
591                 print 'x'*30,'module',self.friendly_name()
592                 print 'x'*20,'<',tag_url
593                 print 'x'*20,'>',edge_url
594                 print diff_output
595
596 ##############################
597     # using fine_grain means replacing only those instances that currently refer to this tag
598     # otherwise, <module>-SVNPATH is replaced unconditionnally
599     def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
600         newtagsfile=tagsfile+".new"
601         tags=open (tagsfile)
602         new=open(newtagsfile,"w")
603
604         matches=0
605         # fine-grain : replace those lines that refer to oldname
606         if fine_grain:
607             if self.options.verbose:
608                 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
609             matcher=re.compile("^(.*)%s(.*)"%oldname)
610             for line in tags.readlines():
611                 if not matcher.match(line):
612                     new.write(line)
613                 else:
614                     (begin,end)=matcher.match(line).groups()
615                     new.write(begin+newname+end+"\n")
616                     matches += 1
617         # brute-force : change uncommented lines that define <module>-SVNPATH
618         else:
619             if self.options.verbose:
620                 print 'Setting %s-SVNPATH for using %s\n\tin %s .. '%(self.name,newname,tagsfile),
621             pattern="\A\s*%s-SVNPATH\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s/[^\s]+"\
622                                           %(self.name,self.name)
623             matcher_module=re.compile(pattern)
624             for line in tags.readlines():
625                 attempt=matcher_module.match(line)
626                 if attempt:
627                     svnpath="%s-SVNPATH"%self.name
628                     replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
629                     new.write(replacement)
630                     matches += 1
631                 else:
632                     new.write(line)
633         tags.close()
634         new.close()
635         os.rename(newtagsfile,tagsfile)
636         if self.options.verbose: print "%d changes"%matches
637         return matches
638
639     def do_tag (self):
640         self.init_moddir()
641         self.init_edge_dir()
642         self.revert_edge_dir()
643         self.update_edge_dir()
644         # parse specfile
645         spec_dict = self.spec_dict()
646         self.show_dict(spec_dict)
647         
648         # side effects
649         edge_url=self.edge_url()
650         old_tag_name = self.tag_name(spec_dict)
651         old_tag_url=self.tag_url(spec_dict)
652         if (self.options.new_version):
653             # new version set on command line
654             spec_dict[self.module_version_varname] = self.options.new_version
655             spec_dict[self.module_taglevel_varname] = 0
656         else:
657             # increment taglevel
658             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
659             spec_dict[self.module_taglevel_varname] = new_taglevel
660
661         # sanity check
662         new_tag_name = self.tag_name(spec_dict)
663         new_tag_url=self.tag_url(spec_dict)
664         self.check_svnpath_exists (edge_url,"edge track")
665         self.check_svnpath_exists (old_tag_url,"previous tag")
666         self.check_svnpath_not_exists (new_tag_url,"new tag")
667
668         # checking for diffs
669         diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
670                             self.options).output_of()
671         if len(diff_output) == 0:
672             if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
673                 return
674
675         # side effect in trunk's specfile
676         self.patch_spec_var(spec_dict)
677
678         # prepare changelog file 
679         # we use the standard subversion magic string (see svn_magic_line)
680         # so we can provide useful information, such as version numbers and diff
681         # in the same file
682         changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
683         file(changelog,"w").write("""Tagging module %s - %s
684
685 %s
686 Please write a changelog for this new tag in the section above
687 """%(self.name,new_tag_name,Module.svn_magic_line))
688
689         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
690             file(changelog,"a").write('DIFF=========\n' + diff_output)
691         
692         if self.options.debug:
693             prompt('Proceed ?')
694
695         # edit it        
696         self.run("%s %s"%(self.options.editor,changelog))
697         # insert changelog in spec
698         if self.options.changelog:
699             self.insert_changelog (changelog,old_tag_name,new_tag_name)
700
701         ## update build
702         try:
703             buildname=Module.config['build']
704         except:
705             buildname="build"
706         if self.options.build_branch:
707             buildname+=":"+self.options.build_branch
708         build = Module(buildname,self.options)
709         build.init_moddir()
710         build.init_edge_dir()
711         build.revert_edge_dir()
712         build.update_edge_dir()
713         
714         tagsfiles=glob(build.edge_dir()+"/*-tags*.mk")
715         tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
716         default_answer = 'y'
717         while True:
718             for (tagsfile,status) in tagsdict.iteritems():
719                 basename=os.path.basename(tagsfile)
720                 print ".................... Dealing with %s"%basename
721                 while tagsdict[tagsfile] == 'todo' :
722                     choice = prompt ("insert %s in %s    "%(new_tag_name,basename),default_answer,
723                                      [ ('y','es'), ('n', 'ext'), ('f','orce'), 
724                                        ('d','iff'), ('r','evert'), ('h','elp') ] ,
725                                      allow_outside=True)
726                     if choice == 'y':
727                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
728                     elif choice == 'n':
729                         print 'Done with %s'%os.path.basename(tagsfile)
730                         tagsdict[tagsfile]='done'
731                     elif choice == 'f':
732                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
733                     elif choice == 'd':
734                         self.run("svn diff %s"%tagsfile)
735                     elif choice == 'r':
736                         self.run("svn revert %s"%tagsfile)
737                     else:
738                         name=self.name
739                         print """y: change %(name)s-SVNPATH only if it currently refers to %(old_tag_name)s
740 f: unconditionnally change any line setting %(name)s-SVNPATH to using %(new_tag_name)s
741 d: show current diff for this tag file
742 r: revert that tag file
743 n: move to next file"""%locals()
744
745             if prompt("Want to review changes on tags files",False):
746                 tagsdict = dict ( [ (x, 'todo') for tagsfile in tagsfiles ] )
747                 default_answer='d'
748             else:
749                 break
750
751         paths=""
752         paths += self.edge_dir() + " "
753         paths += build.edge_dir() + " "
754         self.run_prompt("Review module and build","svn diff " + paths)
755         self.run_prompt("Commit module and build","svn commit --file %s %s"%(changelog,paths))
756         self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
757
758         if self.options.debug:
759             print 'Preserving',changelog
760         else:
761             os.unlink(changelog)
762             
763 ##############################
764     def do_branch (self):
765
766         # save self.branch if any, as a hint for the new branch 
767         # do this before anything else and restore .branch to None, 
768         # as this is part of the class's logic
769         new_trunk_name=None
770         if self.branch:
771             new_trunk_name=self.branch
772             self.branch=None
773
774         # compute diff - a way to initialize the whole stuff
775         # do_diff already does edge_dir initialization
776         # and it checks that edge_url and tag_url exist as well
777         (spec_dict,edge_url,tag_url,diff_listing) = self.do_diff(compute_only=True)
778
779         # the version name in the trunk becomes the new branch name
780         branch_name = spec_dict[self.module_version_varname]
781
782         # figure new branch name (the one for the trunk) if not provided on the command line
783         if not new_trunk_name:
784             # heuristic is to assume 'version' is a dot-separated name
785             # we isolate the rightmost part and try incrementing it by 1
786             version=spec_dict[self.module_version_varname]
787             try:
788                 m=re.compile("\A(?P<leftpart>.+)\.(?P<rightmost>[^\.]+)\Z")
789                 (leftpart,rightmost)=m.match(version).groups()
790                 incremented = int(rightmost)+1
791                 new_trunk_name="%s.%d"%(leftpart,incremented)
792             except:
793                 raise Exception, 'Cannot figure next branch name from %s - exiting'%version
794
795         # record starting point tagname
796         latest_tag_name = self.tag_name(spec_dict)
797
798         print "**********"
799         print "Using starting point %s (%s)"%(tag_url,latest_tag_name)
800         print "Creating branch %s  &  moving trunk to %s"%(branch_name,new_trunk_name)
801         print "**********"
802
803         # print warning if pending diffs
804         if diff_listing:
805             print """*** WARNING : Module %s has pending diffs on its trunk
806 It is safe to proceed, but please note that branch %s
807 will be based on latest tag %s and *not* on the current trunk"""%(self.name,branch_name,latest_tag_name)
808             while True:
809                 answer = prompt ('Are you sure you want to proceed with branching',True,('d','iff'))
810                 if answer is True:
811                     break
812                 elif answer is False:
813                     raise Exception,"User quit"
814                 elif answer == 'd':
815                     print '<<<< %s'%tag_url
816                     print '>>>> %s'%edge_url
817                     print diff_listing
818
819         branch_url = "%s/%s/branches/%s"%(Module.config['svnpath'],self.name,branch_name)
820         self.check_svnpath_not_exists (branch_url,"new branch")
821         
822         # patching trunk
823         spec_dict[self.module_version_varname]=new_trunk_name
824         spec_dict[self.module_taglevel_varname]='0'
825         # remember this in the trunk for easy location of the current branch
826         spec_dict['module_current_branch']=branch_name
827         self.patch_spec_var(spec_dict,True)
828         
829         # create commit log file
830         tmp="/tmp/branching-%d"%os.getpid()
831         f=open(tmp,"w")
832         f.write("Branch %s for module %s created (as new trunk) from tag %s\n"%(new_trunk_name,self.name,latest_tag_name))
833         f.close()
834
835         # we're done, let's commit the stuff
836         command="svn diff %s"%self.edge_dir()
837         self.run_prompt("Review changes in trunk",command)
838         command="svn copy --file %s %s %s"%(tmp,self.edge_url(),branch_url)
839         self.run_prompt("Create branch",command)
840         command="svn commit --file %s %s"%(tmp,self.edge_dir())
841         self.run_prompt("Commit trunk",command)
842         new_tag_url=self.tag_url(spec_dict)
843         command="svn copy --file %s %s %s"%(tmp,self.edge_url(),new_tag_url)
844         self.run_prompt("Create initial tag in trunk",command)
845         os.unlink(tmp)
846
847 ##############################
848 class Main:
849
850     usage="""Usage: %prog options module_desc [ .. module_desc ]
851 Purpose:
852   manage subversion tags and specfile
853   requires the specfile to define *version* and *taglevel*
854   OR alternatively 
855   redirection variables module_version_varname / module_taglevel_varname
856 Trunk:
857   by default, the trunk of modules is taken into account
858   in this case, just mention the module name as <module_desc>
859 Branches:
860   if you wish to work on a branch rather than on the trunk, 
861   you can use something like e.g. Mom:2.1 as <module_desc>
862 More help:
863   see http://svn.planet-lab.org/wiki/ModuleTools
864 """
865
866     modes={ 
867         'list' : "displays a list of available tags or branches",
868         'version' : "check latest specfile and print out details",
869         'diff' : "show difference between module (trunk or branch) and latest tag",
870         'tag'  : """increment taglevel in specfile, insert changelog in specfile,
871                 create new tag and and monitor its adoption in build/*-tags*.mk""",
872         'branch' : """create a branch for this module, from the latest tag on the trunk, 
873                   and change trunk's version number to reflect the new branch name;
874                   you can specify the new branch name by using module:branch""",
875         'sync' : """create a tag from the module
876                 this is a last resort option, mostly for repairs""",
877         }
878
879     silent_modes = ['list']
880
881     def run(self):
882
883         mode=None
884         for function in Main.modes.keys():
885             if sys.argv[0].find(function) >= 0:
886                 mode = function
887                 break
888         if not mode:
889             print "Unsupported command",sys.argv[0]
890             sys.exit(1)
891
892         Main.usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
893         all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
894
895         parser=OptionParser(usage=Main.usage,version=subversion_id)
896         
897         if mode == 'list':
898             parser.add_option("-b","--branches",action="store_true",dest="list_branches",default=False,
899                               help="list branches")
900             parser.add_option("-t","--tags",action="store_false",dest="list_branches",
901                               help="list tags")
902             parser.add_option("-m","--match",action="store",dest="list_pattern",default=None,
903                                help="grep pattern for filtering output")
904             parser.add_option("-x","--exact-match",action="store",dest="list_exact",default=None,
905                                help="exact grep pattern for filtering output")
906         if mode == "tag" or mode == 'branch':
907             parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
908                               help="set new version and reset taglevel to 0")
909         if mode == "tag" :
910             parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
911                               help="do not update changelog section in specfile when tagging")
912             parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
913                               help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
914         if mode == "tag" or mode == "sync" :
915             parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
916                               help="specify editor")
917         if mode == "sync" :
918             parser.add_option("-m","--message", action="store", dest="message", default=None,
919                               help="specify log message")
920         if mode == "diff" :
921             parser.add_option("-o","--only", action="store_true", dest="only", default=False,
922                               help="report diff only for modules that exhibit differences")
923         if mode == "diff" :
924             parser.add_option("-l","--list", action="store_true", dest="list", default=False,
925                               help="just list modules that exhibit differences")
926
927         if mode  == 'version':
928             parser.add_option("-u","--url", action="store_true", dest="show_urls", default=False,
929                               help="display URLs")
930             
931         # default verbosity depending on function - temp
932         parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
933                           help="run on all modules as found in %s"%all_modules)
934         verbose_default=False
935         if mode in ['tag','sync'] : verbose_default = True
936         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=verbose_default, 
937                           help="run in verbose mode")
938         if mode not in ['version','list']:
939             parser.add_option("-q","--quiet", action="store_false", dest="verbose", 
940                               help="run in quiet (non-verbose) mode")
941         parser.add_option("-w","--workdir", action="store", dest="workdir", 
942                           default="%s/%s"%(os.getenv("HOME"),"modules"),
943                           help="""name for dedicated working dir - defaults to ~/modules
944 ** THIS MUST NOT ** be your usual working directory""")
945         parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
946                           help="skip safety checks, such as svn updates -- use with care")
947         parser.add_option("-d","--debug", action="store_true", dest="debug", default=False, 
948                           help="debug mode - mostly more verbose")
949         (options, args) = parser.parse_args()
950         options.mode=mode
951
952         if len(args) == 0:
953             if options.all_modules:
954                 args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
955             else:
956                 parser.print_help()
957                 sys.exit(1)
958         Module.init_homedir(options)
959         for modname in args:
960             module=Module(modname,options)
961             if len(args)>1 and mode not in Main.silent_modes:
962                 print '========================================',module.friendly_name()
963             # call the method called do_<mode>
964             method=Module.__dict__["do_%s"%mode]
965             try:
966                 method(module)
967             except Exception,e:
968                 print 'Skipping failed %s: '%modname,e
969
970 if __name__ == "__main__" :
971     try:
972         Main().run()
973     except KeyboardInterrupt:
974         print '\nBye'
975