5 import sys, os, os.path
9 from optparse import OptionParser
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 ]
19 if default is True: choices.append('[y]')
20 else : choices.append('y')
22 if default is False: choices.append('[n]')
23 else : choices.append('n')
25 for (char,choice) in other_choices:
27 choices.append("["+char+"]"+choice)
29 choices.append("<"+char+">"+choice)
31 answer=raw_input(question + " " + "/".join(choices) + " ? ")
34 answer=answer[0].lower()
36 if 'y' in chars: return 'y'
39 if 'n' in chars: return 'n'
42 for (char,choice) in other_choices:
47 return prompt(question,default,other_choices)
53 editor = os.environ['EDITOR']
61 def print_fold (line):
62 while len(line) >= fold_length:
63 print line[:fold_length],'\\'
64 line=line[fold_length:]
68 def __init__ (self,command,options):
71 self.tmp="/tmp/command-%d"%os.getpid()
74 if self.options.dry_run:
75 print 'dry_run',self.command
77 if self.options.verbose and self.options.mode not in Main.silent_modes:
78 print '+',self.command
80 return os.system(self.command)
82 def run_silent (self):
83 if self.options.dry_run:
84 print 'dry_run',self.command
86 if self.options.verbose:
87 print '+',self.command,' .. ',
89 retcod=os.system(self.command + " &> " + self.tmp)
91 print "FAILED ! -- out+err below (command was %s)"%self.command
92 os.system("cat " + self.tmp)
93 print "FAILED ! -- end of quoted output"
94 elif self.options.verbose:
100 if self.run_silent() !=0:
101 raise Exception,"Command %s failed"%self.command
103 # returns stdout, like bash's $(mycommand)
104 def output_of (self,with_stderr=False):
105 if self.options.dry_run:
106 print 'dry_run',self.command
107 return 'dry_run output'
108 tmp="/tmp/status-%d"%os.getpid()
109 if self.options.debug:
110 print '+',self.command,' .. ',
119 result=file(tmp).read()
121 if self.options.debug:
126 def __init__(self,path,options):
130 def url_exists (self):
131 return os.system("svn list %s &> /dev/null"%self.path) == 0
133 def dir_needs_revert (self):
134 command="svn status %s"%self.path
135 return len(Command(command,self.options).output_of(True)) != 0
136 # turns out it's the same implem.
137 def file_needs_commit (self):
138 command="svn status %s"%self.path
139 return len(Command(command,self.options).output_of(True)) != 0
141 # support for tagged module is minimal, and is for the Build class only
144 svn_magic_line="--This line, and those below, will be ignored--"
146 redirectors=[ # ('module_name_varname','name'),
147 ('module_version_varname','version'),
148 ('module_taglevel_varname','taglevel'), ]
150 # where to store user's config
151 config_storage="CONFIG"
156 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
157 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
158 ("build", "Enter the name of your build module","build"),
159 ('username',"Enter your firstname and lastname for changelogs",""),
160 ("email","Enter your email address for changelogs",""),
164 def prompt_config ():
165 for (key,message,default) in Module.configKeys:
166 Module.config[key]=""
167 while not Module.config[key]:
168 Module.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
171 # for parsing module spec name:branch
172 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
173 # special form for tagged module - for Build
174 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
176 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
178 def __init__ (self,module_spec,options):
180 attempt=Module.matcher_branch_spec.match(module_spec)
182 self.name=attempt.group('name')
183 self.branch=attempt.group('branch')
185 attempt=Module.matcher_tag_spec.match(module_spec)
187 self.name=attempt.group('name')
188 self.tagname=attempt.group('tagname')
190 self.name=module_spec
193 self.module_dir="%s/%s"%(options.workdir,self.name)
195 def friendly_name (self):
196 if hasattr(self,'branch'):
197 return "%s:%s"%(self.name,self.branch)
198 elif hasattr(self,'tagname'):
199 return "%s@%s"%(self.name,self.tagname)
204 if hasattr(self,'branch'):
205 return "%s/branches/%s"%(self.module_dir,self.branch)
206 elif hasattr(self,'tagname'):
207 return "%s/tags/%s"%(self.module_dir,self.tagname)
209 return "%s/trunk"%(self.module_dir)
212 return "%s/tags"%(self.module_dir)
214 def run (self,command):
215 return Command(command,self.options).run()
216 def run_fatal (self,command):
217 return Command(command,self.options).run_fatal()
218 def run_prompt (self,message,command):
219 if not self.options.verbose:
221 choice=prompt(message,True,('s','how'))
225 elif choice is False:
228 print 'About to run:',command
230 question=message+" - want to run " + command
231 if prompt(question,True):
235 def init_homedir (options):
236 topdir=options.workdir
237 if options.verbose and options.mode not in Main.silent_modes:
238 print 'Checking for',topdir
239 storage="%s/%s"%(topdir,Module.config_storage)
240 # sanity check. Either the topdir exists AND we have a config/storage
241 # or topdir does not exist and we create it
242 # to avoid people use their own daily svn repo
243 if os.path.isdir(topdir) and not os.path.isfile(storage):
244 print """The directory %s exists and has no CONFIG file
245 If this is your regular working directory, please provide another one as the
246 module-* commands need a fresh working dir. Make sure that you do not use
247 that for other purposes than tagging"""%topdir
249 if not os.path.isdir (topdir):
250 print "Cannot find",topdir,"let's create it"
251 Module.prompt_config()
252 print "Checking ...",
253 Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
254 Command("svn co -N %s/%s %s/%s"%(Module.config['svnpath'],
255 Module.config['build'],
257 Module.config['build']),options).run_fatal()
262 for (key,message,default) in Module.configKeys:
263 f.write("%s=%s\n"%(key,Module.config[key]))
266 print 'Stored',storage
267 Command("cat %s"%storage,options).run()
271 for line in f.readlines():
272 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
273 Module.config[key]=value
275 if options.verbose and options.mode not in Main.silent_modes:
276 print '******** Using config'
277 for (key,message,default) in Module.configKeys:
278 print '\t',key,'=',Module.config[key]
280 def init_module_dir (self):
281 if self.options.verbose:
282 print 'Checking for',self.module_dir
283 if not os.path.isdir (self.module_dir):
284 self.run_fatal("svn update -N %s"%self.module_dir)
285 if not os.path.isdir (self.module_dir):
286 raise Exception, 'Cannot find %s - check module name'%self.module_dir
288 def init_subdir (self,fullpath):
289 if self.options.verbose:
290 print 'Checking for',fullpath
291 if not os.path.isdir (fullpath):
292 self.run_fatal("svn update -N %s"%fullpath)
294 def revert_subdir (self,fullpath):
295 if self.options.fast_checks:
296 if self.options.verbose: print 'Skipping revert of %s'%fullpath
298 if self.options.verbose:
299 print 'Checking whether',fullpath,'needs being reverted'
300 if Svnpath(fullpath,self.options).dir_needs_revert():
301 self.run_fatal("svn revert -R %s"%fullpath)
303 def update_subdir (self,fullpath):
304 if self.options.fast_checks:
305 if self.options.verbose: print 'Skipping update of %s'%fullpath
307 if self.options.verbose:
308 print 'Updating',fullpath
309 self.run_fatal("svn update -N %s"%fullpath)
311 def init_edge_dir (self):
312 # if branch, edge_dir is two steps down
313 if hasattr(self,'branch'):
314 self.init_subdir("%s/branches"%self.module_dir)
315 elif hasattr(self,'tagname'):
316 self.init_subdir("%s/tags"%self.module_dir)
317 self.init_subdir(self.edge_dir())
319 def revert_edge_dir (self):
320 self.revert_subdir(self.edge_dir())
322 def update_edge_dir (self):
323 self.update_subdir(self.edge_dir())
325 def main_specname (self):
326 attempt="%s/%s.spec"%(self.edge_dir(),self.name)
327 if os.path.isfile (attempt):
330 pattern="%s/*.spec"%self.edge_dir()
332 return glob(pattern)[0]
334 raise Exception, 'Cannot guess specfile for module %s -- pattern was %s'%(self.name,pattern)
336 def all_specnames (self):
337 return glob("%s/*.spec"%self.edge_dir())
339 def parse_spec (self, specfile, varnames):
340 if self.options.verbose:
341 print 'Parsing',specfile,
347 for line in f.readlines():
348 attempt=Module.matcher_rpm_define.match(line)
350 (define,var,value)=attempt.groups()
354 if self.options.debug:
355 print 'found',len(result),'keys'
356 for (k,v) in result.iteritems():
360 # stores in self.module_name_varname the rpm variable to be used for the module's name
361 # and the list of these names in self.varnames
362 def spec_dict (self):
363 specfile=self.main_specname()
364 redirector_keys = [ varname for (varname,default) in Module.redirectors]
365 redirect_dict = self.parse_spec(specfile,redirector_keys)
366 if self.options.debug:
367 print '1st pass parsing done, redirect_dict=',redirect_dict
369 for (varname,default) in Module.redirectors:
370 if redirect_dict.has_key(varname):
371 setattr(self,varname,redirect_dict[varname])
372 varnames += [redirect_dict[varname]]
374 setattr(self,varname,default)
375 varnames += [ default ]
376 self.varnames = varnames
377 result = self.parse_spec (specfile,self.varnames)
378 if self.options.debug:
379 print '2st pass parsing done, varnames=',varnames,'result=',result
382 def patch_spec_var (self, patch_dict,define_missing=False):
383 for specfile in self.all_specnames():
384 # record the keys that were changed
385 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
386 newspecfile=specfile+".new"
387 if self.options.verbose:
388 print 'Patching',specfile,'for',patch_dict.keys()
390 new=open(newspecfile,"w")
392 for line in spec.readlines():
393 attempt=Module.matcher_rpm_define.match(line)
395 (define,var,value)=attempt.groups()
396 if var in patch_dict.keys():
397 if self.options.debug:
398 print 'rewriting %s as %s'%(var,patch_dict[var])
399 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
404 for (key,was_changed) in changed.iteritems():
406 if self.options.debug:
407 print 'rewriting missing %s as %s'%(key,patch_dict[key])
408 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
411 os.rename(newspecfile,specfile)
413 def unignored_lines (self, logfile):
415 exclude="Setting tag %s"%self.name
416 white_line_matcher = re.compile("\A\s*\Z")
417 for logline in file(logfile).readlines():
418 if logline.strip() == Module.svn_magic_line:
420 if logline.find(exclude) >= 0:
422 elif white_line_matcher.match(logline):
425 result.append(logline.strip()+'\n')
428 def insert_changelog (self, logfile, oldtag, newtag):
429 for specfile in self.all_specnames():
430 newspecfile=specfile+".new"
431 if self.options.verbose:
432 print 'Inserting changelog from %s into %s'%(logfile,specfile)
434 new=open(newspecfile,"w")
435 for line in spec.readlines():
437 if re.compile('%changelog').match(line):
438 dateformat="* %a %b %d %Y"
439 datepart=time.strftime(dateformat)
440 logpart="%s <%s> - %s"%(Module.config['username'],
441 Module.config['email'],
443 new.write(datepart+" "+logpart+"\n")
444 for logline in self.unignored_lines(logfile):
445 new.write("- " + logline)
449 os.rename(newspecfile,specfile)
451 def show_dict (self, spec_dict):
452 if self.options.verbose:
453 for (k,v) in spec_dict.iteritems():
457 return "%s/%s"%(Module.config['svnpath'],self.name)
460 if hasattr(self,'branch'):
461 return "%s/branches/%s"%(self.mod_url(),self.branch)
462 elif hasattr(self,'tagname'):
463 return "%s/tags/%s"%(self.mod_url(),self.tagname)
465 return "%s/trunk"%(self.mod_url())
467 def tag_name (self, spec_dict):
469 return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
471 spec_dict[self.module_version_varname],
472 spec_dict[self.module_taglevel_varname])
474 raise Exception, 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
476 def tag_url (self, spec_dict):
477 return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
479 def check_svnpath_exists (self, url, message):
480 if self.options.fast_checks:
482 if self.options.verbose:
483 print 'Checking url (%s) %s'%(url,message),
484 ok=Svnpath(url,self.options).url_exists()
486 if self.options.verbose: print 'exists - OK'
488 if self.options.verbose: print 'KO'
489 raise Exception, 'Could not find %s URL %s'%(message,url)
491 def check_svnpath_not_exists (self, url, message):
492 if self.options.fast_checks:
494 if self.options.verbose:
495 print 'Checking url (%s) %s'%(url,message),
496 ok=not Svnpath(url,self.options).url_exists()
498 if self.options.verbose: print 'does not exist - OK'
500 if self.options.verbose: print 'KO'
501 raise Exception, '%s URL %s already exists - exiting'%(message,url)
503 # locate specfile, parse it, check it and show values
505 ##############################
506 def do_version (self):
507 self.init_module_dir()
509 self.revert_edge_dir()
510 self.update_edge_dir()
511 spec_dict = self.spec_dict()
512 for varname in self.varnames:
513 if not spec_dict.has_key(varname):
514 print 'Could not find %%define for %s'%varname
517 print "%-16s %s"%(varname,spec_dict[varname])
518 if self.options.show_urls:
519 print "%-16s %s"%('edge url',self.edge_url())
520 print "%-16s %s"%('latest tag url',self.tag_url(spec_dict))
521 if self.options.verbose:
522 print "%-16s %s"%('main specfile:',self.main_specname())
523 print "%-16s %s"%('specfiles:',self.all_specnames())
525 ##############################
527 # print 'verbose',self.options.verbose
528 # print 'list_tags',self.options.list_tags
529 # print 'list_branches',self.options.list_branches
530 # print 'all_modules',self.options.all_modules
532 (verbose,branches,pattern,exact) = (self.options.verbose,self.options.list_branches,
533 self.options.list_pattern,self.options.list_exact)
537 if hasattr(self,'branch'):
541 if verbose: grep="%s/$"%exact
542 else: grep="^%s$"%exact
545 extra_command=" | grep %s"%grep
546 extra_message=" matching %s"%grep
549 message="==================== tags for %s"%self.friendly_name()
551 if verbose: command+="--verbose "
552 command += "%s/tags"%self.mod_url()
553 command += extra_command
554 message += extra_message
555 if verbose: print message
559 message="==================== branches for %s"%self.friendly_name()
561 if verbose: command+="--verbose "
562 command += "%s/branches"%self.mod_url()
563 command += extra_command
564 message += extra_message
565 if verbose: print message
568 ##############################
569 sync_warning="""*** WARNING
570 The module-sync function has the following limitations
571 * it does not handle changelogs
572 * it does not scan the -tags*.mk files to adopt the new tags"""
575 if self.options.verbose:
576 print Module.sync_warning
577 if not prompt('Want to proceed anyway'):
580 self.init_module_dir()
582 self.revert_edge_dir()
583 self.update_edge_dir()
584 spec_dict = self.spec_dict()
586 edge_url=self.edge_url()
587 tag_name=self.tag_name(spec_dict)
588 tag_url=self.tag_url(spec_dict)
589 # check the tag does not exist yet
590 self.check_svnpath_not_exists(tag_url,"new tag")
592 if self.options.message:
593 svnopt='--message "%s"'%self.options.message
595 svnopt='--editor-cmd=%s'%self.options.editor
596 self.run_prompt("Create initial tag",
597 "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
599 ##############################
600 def do_diff (self,compute_only=False):
601 self.init_module_dir()
603 self.revert_edge_dir()
604 self.update_edge_dir()
605 spec_dict = self.spec_dict()
606 self.show_dict(spec_dict)
608 edge_url=self.edge_url()
609 tag_url=self.tag_url(spec_dict)
610 self.check_svnpath_exists(edge_url,"edge track")
611 self.check_svnpath_exists(tag_url,"latest tag")
612 command="svn diff %s %s"%(tag_url,edge_url)
614 if self.options.verbose:
615 print 'Getting diff with %s'%command
616 diff_output = Command(command,self.options).output_of()
617 # if used as a utility
619 return (spec_dict,edge_url,tag_url,diff_output)
620 # otherwise print the result
621 if self.options.list:
625 if not self.options.only or diff_output:
626 print 'x'*30,'module',self.friendly_name()
627 print 'x'*20,'<',tag_url
628 print 'x'*20,'>',edge_url
631 ##############################
632 # using fine_grain means replacing only those instances that currently refer to this tag
633 # otherwise, <module>-SVNPATH is replaced unconditionnally
634 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
635 newtagsfile=tagsfile+".new"
637 new=open(newtagsfile,"w")
640 # fine-grain : replace those lines that refer to oldname
642 if self.options.verbose:
643 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
644 matcher=re.compile("^(.*)%s(.*)"%oldname)
645 for line in tags.readlines():
646 if not matcher.match(line):
649 (begin,end)=matcher.match(line).groups()
650 new.write(begin+newname+end+"\n")
652 # brute-force : change uncommented lines that define <module>-SVNPATH
654 if self.options.verbose:
655 print 'Searching for -SVNPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
656 pattern="\A\s*(?P<make_name>[^\s]+)-SVNPATH\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s/[^\s]+"\
658 matcher_module=re.compile(pattern)
659 for line in tags.readlines():
660 attempt=matcher_module.match(line)
662 svnpath="%s-SVNPATH"%(attempt.group('make_name'))
663 if self.options.verbose:
665 replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
666 new.write(replacement)
672 os.rename(newtagsfile,tagsfile)
673 if self.options.verbose: print "%d changes"%matches
677 self.init_module_dir()
679 self.revert_edge_dir()
680 self.update_edge_dir()
682 spec_dict = self.spec_dict()
683 self.show_dict(spec_dict)
686 edge_url=self.edge_url()
687 old_tag_name = self.tag_name(spec_dict)
688 old_tag_url=self.tag_url(spec_dict)
689 if (self.options.new_version):
690 # new version set on command line
691 spec_dict[self.module_version_varname] = self.options.new_version
692 spec_dict[self.module_taglevel_varname] = 0
695 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
696 spec_dict[self.module_taglevel_varname] = new_taglevel
699 new_tag_name = self.tag_name(spec_dict)
700 new_tag_url=self.tag_url(spec_dict)
701 self.check_svnpath_exists (edge_url,"edge track")
702 self.check_svnpath_exists (old_tag_url,"previous tag")
703 self.check_svnpath_not_exists (new_tag_url,"new tag")
706 diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
707 self.options).output_of()
708 if len(diff_output) == 0:
709 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
712 # side effect in trunk's specfile
713 self.patch_spec_var(spec_dict)
715 # prepare changelog file
716 # we use the standard subversion magic string (see svn_magic_line)
717 # so we can provide useful information, such as version numbers and diff
719 changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
720 file(changelog,"w").write("""Setting tag %s
723 Please write a changelog for this new tag in the section above
724 """%(new_tag_name,Module.svn_magic_line))
726 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
727 file(changelog,"a").write('DIFF=========\n' + diff_output)
729 if self.options.debug:
733 self.run("%s %s"%(self.options.editor,changelog))
734 # insert changelog in spec
735 if self.options.changelog:
736 self.insert_changelog (changelog,old_tag_name,new_tag_name)
740 buildname=Module.config['build']
743 if self.options.build_branch:
744 buildname+=":"+self.options.build_branch
745 build = Module(buildname,self.options)
746 build.init_module_dir()
747 build.init_edge_dir()
748 build.revert_edge_dir()
749 build.update_edge_dir()
751 tagsfiles=glob(build.edge_dir()+"/*-tags*.mk")
752 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
755 for (tagsfile,status) in tagsdict.iteritems():
756 basename=os.path.basename(tagsfile)
757 print ".................... Dealing with %s"%basename
758 while tagsdict[tagsfile] == 'todo' :
759 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
760 [ ('y','es'), ('n', 'ext'), ('f','orce'),
761 ('d','iff'), ('r','evert'), ('h','elp') ] ,
764 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
766 print 'Done with %s'%os.path.basename(tagsfile)
767 tagsdict[tagsfile]='done'
769 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
771 self.run("svn diff %s"%tagsfile)
773 self.run("svn revert %s"%tagsfile)
776 print """y: change %(name)s-SVNPATH only if it currently refers to %(old_tag_name)s
777 f: unconditionnally change any line setting %(name)s-SVNPATH to using %(new_tag_name)s
778 d: show current diff for this tag file
779 r: revert that tag file
780 n: move to next file"""%locals()
782 if prompt("Want to review changes on tags files",False):
783 tagsdict = dict ( [ (x, 'todo') for tagsfile in tagsfiles ] )
789 paths += self.edge_dir() + " "
790 paths += build.edge_dir() + " "
791 self.run_prompt("Review module and build","svn diff " + paths)
792 self.run_prompt("Commit module and build","svn commit --file %s %s"%(changelog,paths))
793 self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
795 if self.options.debug:
796 print 'Preserving',changelog
800 ##############################
801 def do_branch (self):
803 # save self.branch if any, as a hint for the new branch
804 # do this before anything else and restore .branch to None,
805 # as this is part of the class's logic
807 if hasattr(self,'branch'):
808 new_trunk_name=self.branch
810 elif self.options.new_version:
811 new_trunk_name = self.options.new_version
813 # compute diff - a way to initialize the whole stuff
814 # do_diff already does edge_dir initialization
815 # and it checks that edge_url and tag_url exist as well
816 (spec_dict,edge_url,tag_url,diff_listing) = self.do_diff(compute_only=True)
818 # the version name in the trunk becomes the new branch name
819 branch_name = spec_dict[self.module_version_varname]
821 # figure new branch name (the one for the trunk) if not provided on the command line
822 if not new_trunk_name:
823 # heuristic is to assume 'version' is a dot-separated name
824 # we isolate the rightmost part and try incrementing it by 1
825 version=spec_dict[self.module_version_varname]
827 m=re.compile("\A(?P<leftpart>.+)\.(?P<rightmost>[^\.]+)\Z")
828 (leftpart,rightmost)=m.match(version).groups()
829 incremented = int(rightmost)+1
830 new_trunk_name="%s.%d"%(leftpart,incremented)
832 raise Exception, 'Cannot figure next branch name from %s - exiting'%version
834 # record starting point tagname
835 latest_tag_name = self.tag_name(spec_dict)
838 print "Using starting point %s (%s)"%(tag_url,latest_tag_name)
839 print "Creating branch %s & moving trunk to %s"%(branch_name,new_trunk_name)
842 # print warning if pending diffs
844 print """*** WARNING : Module %s has pending diffs on its trunk
845 It is safe to proceed, but please note that branch %s
846 will be based on latest tag %s and *not* on the current trunk"""%(self.name,branch_name,latest_tag_name)
848 answer = prompt ('Are you sure you want to proceed with branching',True,('d','iff'))
851 elif answer is False:
852 raise Exception,"User quit"
854 print '<<<< %s'%tag_url
855 print '>>>> %s'%edge_url
858 branch_url = "%s/%s/branches/%s"%(Module.config['svnpath'],self.name,branch_name)
859 self.check_svnpath_not_exists (branch_url,"new branch")
862 spec_dict[self.module_version_varname]=new_trunk_name
863 spec_dict[self.module_taglevel_varname]='0'
864 # remember this in the trunk for easy location of the current branch
865 spec_dict['module_current_branch']=branch_name
866 self.patch_spec_var(spec_dict,True)
868 # create commit log file
869 tmp="/tmp/branching-%d"%os.getpid()
871 f.write("Branch %s for module %s created (as new trunk) from tag %s\n"%(new_trunk_name,self.name,latest_tag_name))
874 # we're done, let's commit the stuff
875 command="svn diff %s"%self.edge_dir()
876 self.run_prompt("Review changes in trunk",command)
877 command="svn copy --file %s %s %s"%(tmp,self.edge_url(),branch_url)
878 self.run_prompt("Create branch",command)
879 command="svn commit --file %s %s"%(tmp,self.edge_dir())
880 self.run_prompt("Commit trunk",command)
881 new_tag_url=self.tag_url(spec_dict)
882 command="svn copy --file %s %s %s"%(tmp,self.edge_url(),new_tag_url)
883 self.run_prompt("Create initial tag in trunk",command)
886 ##############################
889 def __init__(self, package, module, svnpath, spec):
894 self.specpath="%s/%s"%(svnpath,spec)
895 self.basename=os.path.basename(svnpath)
897 # returns a http URL to the trac path where full diff can be viewed (between self and pkg)
898 # typically http://svn.planet-lab.org/changeset?old_path=Monitor%2Ftags%2FMonitor-1.0-7&new_path=Monitor%2Ftags%2FMonitor-1.0-13
899 # xxx quick & dirty: rough url parsing
900 def trac_full_diff (self, pkg):
901 matcher=re.compile("\A(?P<method>.*)://(?P<hostname>[^/]+)/(svn/)?(?P<path>.*)\Z")
902 self_match=matcher.match(self.svnpath)
903 pkg_match=matcher.match(pkg.svnpath)
904 if self_match and pkg_match:
905 (method,hostname,svn,path)=self_match.groups()
906 self_path=path.replace("/","%2F")
907 pkg_path=pkg_match.group('path').replace("/","%2F")
908 return "%s://%s/changeset?old_path=%s&new_path=%s"%(method,hostname,self_path,pkg_path)
913 return "[%s %s] [%s (spec)]"%(self.svnpath,self.basename,self.specpath)
915 class Build (Module):
917 # we cannot get build's svnpath as for other packages as we'd get something in svn+ssh
919 def __init__ (self, buildtag,options):
920 self.buildtag=buildtag
921 # if the buildtag start with a : (to use a branch rather than a tag)
922 if buildtag.find(':') == 0 :
923 module_name="build%(buildtag)s"%locals()
924 self.display=buildtag[1:]
925 self.svnpath="http://svn.planet-lab.org/svn/build/branches/%s"%self.display
927 module_name="build@%(buildtag)s"%locals()
928 self.display=buildtag
929 self.svnpath="http://svn.planet-lab.org/svn/build/tags/%s"%self.buildtag
930 Module.__init__(self,module_name,options)
933 def get_distro_from_distrotag (distrotag):
934 # mhh: remove -tag* from distrotags to get distro
935 n=distrotag.find('-tag')
941 def get_packages (self,distrotag):
943 distro=Build.get_distro_from_distrotag(distrotag)
946 make_options="--no-print-directory -C %s stage1=true PLDISTRO=%s PLDISTROTAGS=%s 2> /dev/null"%(self.edge_dir(),distro,distrotag)
947 command="make %s packages"%make_options
948 make_packages=Command(command,self.options).output_of()
949 pkg_line=re.compile("\Apackage=(?P<package>[^\s]+)\s+ref_module=(?P<module>[^\s]+)\s.*\Z")
950 for line in make_packages.split("\n"):
953 attempt=pkg_line.match(line)
954 if line and not attempt:
956 print "WARNING: line not understood from make packages"
957 print "in dir %s"%self.edge_dir
958 print "with options",make_options
962 (package,module) = (attempt.group('package'),attempt.group('module'))
963 command="make %s +%s-SVNPATH"%(make_options,module)
964 svnpath=Command(command,self.options).output_of().strip()
965 command="make %s +%s-SPEC"%(make_options,package)
966 spec=Command(command,self.options).output_of().strip()
967 result[package]=Package(package,module,svnpath,spec)
970 def get_distrotags (self):
971 return [os.path.basename(p) for p in glob("%s/*tags*mk"%self.edge_dir())]
978 def key(self, frompath,topath):
979 return frompath+'-to-'+topath
981 def fetch (self, frompath, topath):
982 key=self.key(frompath,topath)
983 if not self._cache.has_key(key):
985 return self._cache[key]
987 def store (self, frompath, topath, diff):
988 key=self.key(frompath,topath)
989 self._cache[key]=diff
993 # header in diff output
994 discard_matcher=re.compile("\A(\+\+\+|---).*")
997 def do_changelog (buildtag_new,buildtag_old,options):
1001 (build_new,build_old) = (Build (buildtag_new,options), Build (buildtag_old,options))
1002 print "= build tag %s to %s = #build-%s"%(build_old.display,build_new.display,build_new.display)
1003 for b in (build_new,build_old):
1007 # find out the tags files that are common, unless option was specified
1008 if options.distrotags:
1009 distrotags=options.distrotags
1011 distrotags_new=build_new.get_distrotags()
1012 distrotags_old=build_old.get_distrotags()
1013 distrotags = list(set(distrotags_new).intersection(set(distrotags_old)))
1015 if options.verbose: print "Found distrotags",distrotags
1016 first_distrotag=True
1017 diffcache = DiffCache()
1018 for distrotag in distrotags:
1019 distro=Build.get_distro_from_distrotag(distrotag)
1023 first_distrotag=False
1026 print '== distro %s (%s to %s) == #distro-%s-%s'%(distrotag,build_old.display,build_new.display,distro,build_new.display)
1027 print ' * from %s/%s'%(build_old.svnpath,distrotag)
1028 print ' * to %s/%s'%(build_new.svnpath,distrotag)
1030 # parse make packages
1031 packages_new=build_new.get_packages(distrotag)
1032 pnames_new=set(packages_new.keys())
1033 if options.verbose: print 'got packages for ',build_new.display
1034 packages_old=build_old.get_packages(distrotag)
1035 pnames_old=set(packages_old.keys())
1036 if options.verbose: print 'got packages for ',build_old.display
1038 # get created, deprecated, and preserved package names
1039 pnames_created = list(pnames_new-pnames_old)
1040 pnames_created.sort()
1041 pnames_deprecated = list(pnames_old-pnames_new)
1042 pnames_deprecated.sort()
1043 pnames = list(pnames_new.intersection(pnames_old))
1046 if options.verbose: print "Found new/deprecated/preserved pnames",pnames_new,pnames_deprecated,pnames
1048 # display created and deprecated
1049 for name in pnames_created:
1050 print '=== %s : new package %s -- appeared in %s === #package-%s-%s-%s'%(
1051 distrotag,name,build_new.display,name,distro,build_new.display)
1052 pobj=packages_new[name]
1053 print ' * %s'%pobj.details()
1054 for name in pnames_deprecated:
1055 print '=== %s : package %s -- deprecated, last occurrence in %s === #package-%s-%s-%s'%(
1056 distrotag,name,build_old.display,name,distro,build_new.display)
1057 pobj=packages_old[name]
1058 if not pobj.svnpath:
1059 print ' * codebase stored in CVS, specfile is %s'%pobj.spec
1061 print ' * %s'%pobj.details()
1063 # display other packages
1065 (pobj_new,pobj_old)=(packages_new[name],packages_old[name])
1066 if options.verbose: print "Dealing with package",name
1067 if pobj_old.specpath == pobj_new.specpath:
1069 specdiff = diffcache.fetch(pobj_old.specpath,pobj_new.specpath)
1070 if specdiff is None:
1071 command="svn diff %s %s"%(pobj_old.specpath,pobj_new.specpath)
1072 specdiff=Command(command,options).output_of()
1073 diffcache.store(pobj_old.specpath,pobj_new.specpath,specdiff)
1075 if options.verbose: print 'got diff from cache'
1078 print '=== %s - %s to %s : package %s === #package-%s-%s-%s'%(
1079 distrotag,build_old.display,build_new.display,name,name,distro,build_new.display)
1080 print ' * from %s to %s'%(pobj_old.details(),pobj_new.details())
1081 trac_diff_url=pobj_old.trac_full_diff(pobj_new)
1083 print ' * [%s View full diff]'%trac_diff_url
1085 for line in specdiff.split('\n'):
1088 if Release.discard_matcher.match(line):
1090 if line[0] in ['@']:
1092 elif line[0] in ['+','-']:
1096 ##############################
1099 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1100 module-tools : a set of tools to manage subversion tags and specfile
1101 requires the specfile to either
1102 * define *version* and *taglevel*
1104 * define redirection variables module_version_varname / module_taglevel_varname
1106 by default, the trunk of modules is taken into account
1107 in this case, just mention the module name as <module_desc>
1109 if you wish to work on a branch rather than on the trunk,
1110 you can use something like e.g. Mom:2.1 as <module_desc>
1112 release_usage="""Usage: %prog [options] tag1 .. tagn
1113 Extract release notes from the changes in specfiles between several build tags, latest first
1115 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1116 You can refer to a (build) branch by prepending a colon, like in
1117 release-changelog :4.2 4.2-rc25
1119 common_usage="""More help:
1120 see http://svn.planet-lab.org/wiki/ModuleTools"""
1123 'list' : "displays a list of available tags or branches",
1124 'version' : "check latest specfile and print out details",
1125 'diff' : "show difference between module (trunk or branch) and latest tag",
1126 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1127 create new tag and and monitor its adoption in build/*-tags*.mk""",
1128 'branch' : """create a branch for this module, from the latest tag on the trunk,
1129 and change trunk's version number to reflect the new branch name;
1130 you can specify the new branch name by using module:branch""",
1131 'sync' : """create a tag from the module
1132 this is a last resort option, mostly for repairs""",
1133 'changelog' : """extract changelog between build tags
1134 expected arguments are a list of tags""",
1137 silent_modes = ['list']
1138 release_modes = ['changelog']
1141 def optparse_list (option, opt, value, parser):
1143 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1145 setattr(parser.values,option.dest,value.split())
1150 for function in Main.modes.keys():
1151 if sys.argv[0].find(function) >= 0:
1155 print "Unsupported command",sys.argv[0]
1156 print "Supported commands:" + Modes.modes.keys.join(" ")
1159 if mode not in Main.release_modes:
1160 usage = Main.module_usage
1161 usage += Main.common_usage
1162 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1164 usage = Main.release_usage
1165 usage += Main.common_usage
1167 parser=OptionParser(usage=usage,version=subversion_id)
1170 parser.add_option("-b","--branches",action="store_true",dest="list_branches",default=False,
1171 help="list branches")
1172 parser.add_option("-t","--tags",action="store_false",dest="list_branches",
1174 parser.add_option("-m","--match",action="store",dest="list_pattern",default=None,
1175 help="grep pattern for filtering output")
1176 parser.add_option("-x","--exact-match",action="store",dest="list_exact",default=None,
1177 help="exact grep pattern for filtering output")
1178 if mode == "tag" or mode == 'branch':
1179 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1180 help="set new version and reset taglevel to 0")
1182 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1183 help="do not update changelog section in specfile when tagging")
1184 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1185 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1186 if mode == "tag" or mode == "sync" :
1187 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1188 help="specify editor")
1190 parser.add_option("-m","--message", action="store", dest="message", default=None,
1191 help="specify log message")
1193 parser.add_option("-o","--only", action="store_true", dest="only", default=False,
1194 help="report diff only for modules that exhibit differences")
1196 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1197 help="just list modules that exhibit differences")
1199 if mode == 'version':
1200 parser.add_option("-u","--url", action="store_true", dest="show_urls", default=False,
1201 help="display URLs")
1203 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1204 if mode not in Main.release_modes:
1205 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1206 help="run on all modules as found in %s"%default_modules_list)
1207 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1208 help="run on all modules found in specified file")
1210 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1211 help="dry run - shell commands are only displayed")
1212 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1213 default=[], nargs=1,type="string",
1214 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1215 -- can be set multiple times, or use quotes""")
1217 parser.add_option("-w","--workdir", action="store", dest="workdir",
1218 default="%s/%s"%(os.getenv("HOME"),"modules"),
1219 help="""name for dedicated working dir - defaults to ~/modules
1220 ** THIS MUST NOT ** be your usual working directory""")
1221 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1222 help="skip safety checks, such as svn updates -- use with care")
1224 # default verbosity depending on function - temp
1225 verbose_modes= ['tag','sync']
1227 if mode not in verbose_modes:
1228 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1229 help="run in verbose mode")
1231 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1232 help="run in quiet (non-verbose) mode")
1233 # parser.add_option("-d","--debug", action="store_true", dest="debug", default=False,
1234 # help="debug mode - mostly more verbose")
1235 (options, args) = parser.parse_args()
1237 if not hasattr(options,'dry_run'):
1238 options.dry_run=False
1241 ########## release-*
1242 if mode in Main.release_modes :
1243 ########## changelog
1247 Module.init_homedir(options)
1248 for n in range(len(args)-1):
1249 [t_new,t_old]=args[n:n+2]
1250 Release.do_changelog (t_new,t_old,options)
1254 if options.all_modules:
1255 options.modules_list=default_modules_list
1256 if options.modules_list:
1257 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1261 Module.init_homedir(options)
1262 for modname in args:
1263 module=Module(modname,options)
1264 if len(args)>1 and mode not in Main.silent_modes:
1265 print '========================================',module.friendly_name()
1266 # call the method called do_<mode>
1267 method=Module.__dict__["do_%s"%mode]
1271 print 'Skipping failed %s: '%modname,e
1273 ####################
1274 if __name__ == "__main__" :
1277 except KeyboardInterrupt: