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