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']
59 def __init__ (self,command,options):
62 self.tmp="/tmp/command-%d"%os.getpid()
65 if self.options.dry_run:
66 print 'dry_run',self.command
68 if self.options.verbose and self.options.mode not in Main.silent_modes:
69 print '+',self.command
71 return os.system(self.command)
73 def run_silent (self):
74 if self.options.dry_run:
75 print 'dry_run',self.command
77 if self.options.verbose:
78 print '+',self.command,' .. ',
80 retcod=os.system(self.command + " &> " + self.tmp)
82 print "FAILED ! -- out+err below (command was %s)"%self.command
83 os.system("cat " + self.tmp)
84 print "FAILED ! -- end of quoted output"
85 elif self.options.verbose:
91 if self.run_silent() !=0:
92 raise Exception,"Command %s failed"%self.command
94 # returns stdout, like bash's $(mycommand)
95 def output_of (self,with_stderr=False):
96 if self.options.dry_run:
97 print 'dry_run',self.command
98 return 'dry_run output'
99 tmp="/tmp/status-%d"%os.getpid()
100 if self.options.debug:
101 print '+',self.command,' .. ',
110 result=file(tmp).read()
112 if self.options.debug:
117 def __init__(self,path,options):
121 def url_exists (self):
122 return os.system("svn list %s &> /dev/null"%self.path) == 0
124 def dir_needs_revert (self):
125 command="svn status %s"%self.path
126 return len(Command(command,self.options).output_of(True)) != 0
127 # turns out it's the same implem.
128 def file_needs_commit (self):
129 command="svn status %s"%self.path
130 return len(Command(command,self.options).output_of(True)) != 0
132 # support for tagged module is minimal, and is for the Build class only
135 svn_magic_line="--This line, and those below, will be ignored--"
137 redirectors=[ # ('module_name_varname','name'),
138 ('module_version_varname','version'),
139 ('module_taglevel_varname','taglevel'), ]
141 # where to store user's config
142 config_storage="CONFIG"
147 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
148 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
149 ("build", "Enter the name of your build module","build"),
150 ('username',"Enter your firstname and lastname for changelogs",""),
151 ("email","Enter your email address for changelogs",""),
155 def prompt_config ():
156 for (key,message,default) in Module.configKeys:
157 Module.config[key]=""
158 while not Module.config[key]:
159 Module.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
162 # for parsing module spec name:branch
163 matcher_branch_spec=re.compile("\A(?P<name>[\w-]+):(?P<branch>[\w\.-]+)\Z")
164 # special form for tagged module - for Build
165 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
167 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
169 def __init__ (self,module_spec,options):
171 attempt=Module.matcher_branch_spec.match(module_spec)
173 self.name=attempt.group('name')
174 self.branch=attempt.group('branch')
176 attempt=Module.matcher_tag_spec.match(module_spec)
178 self.name=attempt.group('name')
179 self.tagname=attempt.group('tagname')
181 self.name=module_spec
184 self.module_dir="%s/%s"%(options.workdir,self.name)
186 def friendly_name (self):
187 if hasattr(self,'branch'):
188 return "%s:%s"%(self.name,self.branch)
189 elif hasattr(self,'tagname'):
190 return "%s@%s"%(self.name,self.tagname)
195 if hasattr(self,'branch'):
196 return "%s/branches/%s"%(self.module_dir,self.branch)
197 elif hasattr(self,'tagname'):
198 return "%s/tags/%s"%(self.module_dir,self.tagname)
200 return "%s/trunk"%(self.module_dir)
203 return "%s/tags"%(self.module_dir)
205 def run (self,command):
206 return Command(command,self.options).run()
207 def run_fatal (self,command):
208 return Command(command,self.options).run_fatal()
209 def run_prompt (self,message,command):
210 if not self.options.verbose:
212 choice=prompt(message,True,('s','how'))
216 elif choice is False:
219 print 'About to run:',command
221 question=message+" - want to run " + command
222 if prompt(question,True):
226 def init_homedir (options):
227 topdir=options.workdir
228 if options.verbose and options.mode not in Main.silent_modes:
229 print 'Checking for',topdir
230 storage="%s/%s"%(topdir,Module.config_storage)
231 # sanity check. Either the topdir exists AND we have a config/storage
232 # or topdir does not exist and we create it
233 # to avoid people use their own daily svn repo
234 if os.path.isdir(topdir) and not os.path.isfile(storage):
235 print """The directory %s exists and has no CONFIG file
236 If this is your regular working directory, please provide another one as the
237 module-* commands need a fresh working dir. Make sure that you do not use
238 that for other purposes than tagging"""%topdir
240 if not os.path.isdir (topdir):
241 print "Cannot find",topdir,"let's create it"
242 Module.prompt_config()
243 print "Checking ...",
244 Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
245 Command("svn co -N %s/%s %s/%s"%(Module.config['svnpath'],
246 Module.config['build'],
248 Module.config['build']),options).run_fatal()
253 for (key,message,default) in Module.configKeys:
254 f.write("%s=%s\n"%(key,Module.config[key]))
257 print 'Stored',storage
258 Command("cat %s"%storage,options).run()
262 for line in f.readlines():
263 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
264 Module.config[key]=value
266 if options.verbose and options.mode not in Main.silent_modes:
267 print '******** Using config'
268 for (key,message,default) in Module.configKeys:
269 print '\t',key,'=',Module.config[key]
271 def init_module_dir (self):
272 if self.options.verbose:
273 print 'Checking for',self.module_dir
274 if not os.path.isdir (self.module_dir):
275 self.run_fatal("svn update -N %s"%self.module_dir)
276 if not os.path.isdir (self.module_dir):
277 raise Exception, 'Cannot find %s - check module name'%self.module_dir
279 def init_subdir (self,fullpath):
280 if self.options.verbose:
281 print 'Checking for',fullpath
282 if not os.path.isdir (fullpath):
283 self.run_fatal("svn update -N %s"%fullpath)
285 def revert_subdir (self,fullpath):
286 if self.options.fast_checks:
287 if self.options.verbose: print 'Skipping revert of %s'%fullpath
289 if self.options.verbose:
290 print 'Checking whether',fullpath,'needs being reverted'
291 if Svnpath(fullpath,self.options).dir_needs_revert():
292 self.run_fatal("svn revert -R %s"%fullpath)
294 def update_subdir (self,fullpath):
295 if self.options.fast_checks:
296 if self.options.verbose: print 'Skipping update of %s'%fullpath
298 if self.options.verbose:
299 print 'Updating',fullpath
300 self.run_fatal("svn update -N %s"%fullpath)
302 def init_edge_dir (self):
303 # if branch, edge_dir is two steps down
304 if hasattr(self,'branch'):
305 self.init_subdir("%s/branches"%self.module_dir)
306 elif hasattr(self,'tagname'):
307 self.init_subdir("%s/tags"%self.module_dir)
308 self.init_subdir(self.edge_dir())
310 def revert_edge_dir (self):
311 self.revert_subdir(self.edge_dir())
313 def update_edge_dir (self):
314 self.update_subdir(self.edge_dir())
316 def main_specname (self):
317 attempt="%s/%s.spec"%(self.edge_dir(),self.name)
318 if os.path.isfile (attempt):
322 return glob("%s/*.spec"%self.edge_dir())[0]
324 raise Exception, 'Cannot guess specfile for module %s'%self.name
326 def all_specnames (self):
327 return glob("%s/*.spec"%self.edge_dir())
329 def parse_spec (self, specfile, varnames):
330 if self.options.verbose:
331 print 'Parsing',specfile,
337 for line in f.readlines():
338 attempt=Module.matcher_rpm_define.match(line)
340 (define,var,value)=attempt.groups()
344 if self.options.debug:
345 print 'found',len(result),'keys'
346 for (k,v) in result.iteritems():
350 # stores in self.module_name_varname the rpm variable to be used for the module's name
351 # and the list of these names in self.varnames
352 def spec_dict (self):
353 specfile=self.main_specname()
354 redirector_keys = [ varname for (varname,default) in Module.redirectors]
355 redirect_dict = self.parse_spec(specfile,redirector_keys)
356 if self.options.debug:
357 print '1st pass parsing done, redirect_dict=',redirect_dict
359 for (varname,default) in Module.redirectors:
360 if redirect_dict.has_key(varname):
361 setattr(self,varname,redirect_dict[varname])
362 varnames += [redirect_dict[varname]]
364 setattr(self,varname,default)
365 varnames += [ default ]
366 self.varnames = varnames
367 result = self.parse_spec (specfile,self.varnames)
368 if self.options.debug:
369 print '2st pass parsing done, varnames=',varnames,'result=',result
372 def patch_spec_var (self, patch_dict,define_missing=False):
373 for specfile in self.all_specnames():
374 # record the keys that were changed
375 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
376 newspecfile=specfile+".new"
377 if self.options.verbose:
378 print 'Patching',specfile,'for',patch_dict.keys()
380 new=open(newspecfile,"w")
382 for line in spec.readlines():
383 attempt=Module.matcher_rpm_define.match(line)
385 (define,var,value)=attempt.groups()
386 if var in patch_dict.keys():
387 if self.options.debug:
388 print 'rewriting %s as %s'%(var,patch_dict[var])
389 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
394 for (key,was_changed) in changed.iteritems():
396 if self.options.debug:
397 print 'rewriting missing %s as %s'%(key,patch_dict[key])
398 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
401 os.rename(newspecfile,specfile)
403 def unignored_lines (self, logfile):
405 exclude="Tagging module %s"%self.name
406 white_line_matcher = re.compile("\A\s*\Z")
407 for logline in file(logfile).readlines():
408 if logline.strip() == Module.svn_magic_line:
410 if logline.find(exclude) >= 0:
412 elif white_line_matcher.match(logline):
415 result.append(logline.strip()+'\n')
418 def insert_changelog (self, logfile, oldtag, newtag):
419 for specfile in self.all_specnames():
420 newspecfile=specfile+".new"
421 if self.options.verbose:
422 print 'Inserting changelog from %s into %s'%(logfile,specfile)
424 new=open(newspecfile,"w")
425 for line in spec.readlines():
427 if re.compile('%changelog').match(line):
428 dateformat="* %a %b %d %Y"
429 datepart=time.strftime(dateformat)
430 logpart="%s <%s> - %s"%(Module.config['username'],
431 Module.config['email'],
433 new.write(datepart+" "+logpart+"\n")
434 for logline in self.unignored_lines(logfile):
435 new.write("- " + logline)
439 os.rename(newspecfile,specfile)
441 def show_dict (self, spec_dict):
442 if self.options.verbose:
443 for (k,v) in spec_dict.iteritems():
447 return "%s/%s"%(Module.config['svnpath'],self.name)
450 if hasattr(self,'branch'):
451 return "%s/branches/%s"%(self.mod_url(),self.branch)
452 elif hasattr(self,'tagname'):
453 return "%s/tags/%s"%(self.mod_url(),self.tagname)
455 return "%s/trunk"%(self.mod_url())
457 def tag_name (self, spec_dict):
459 return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
461 spec_dict[self.module_version_varname],
462 spec_dict[self.module_taglevel_varname])
464 raise Exception, 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
466 def tag_url (self, spec_dict):
467 return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
469 def check_svnpath_exists (self, url, message):
470 if self.options.fast_checks:
472 if self.options.verbose:
473 print 'Checking url (%s) %s'%(url,message),
474 ok=Svnpath(url,self.options).url_exists()
476 if self.options.verbose: print 'exists - OK'
478 if self.options.verbose: print 'KO'
479 raise Exception, 'Could not find %s URL %s'%(message,url)
481 def check_svnpath_not_exists (self, url, message):
482 if self.options.fast_checks:
484 if self.options.verbose:
485 print 'Checking url (%s) %s'%(url,message),
486 ok=not Svnpath(url,self.options).url_exists()
488 if self.options.verbose: print 'does not exist - OK'
490 if self.options.verbose: print 'KO'
491 raise Exception, '%s URL %s already exists - exiting'%(message,url)
493 # locate specfile, parse it, check it and show values
495 ##############################
496 def do_version (self):
497 self.init_module_dir()
499 self.revert_edge_dir()
500 self.update_edge_dir()
501 spec_dict = self.spec_dict()
502 for varname in self.varnames:
503 if not spec_dict.has_key(varname):
504 print 'Could not find %%define for %s'%varname
507 print "%-16s %s"%(varname,spec_dict[varname])
508 if self.options.show_urls:
509 print "%-16s %s"%('edge url',self.edge_url())
510 print "%-16s %s"%('latest tag url',self.tag_url(spec_dict))
511 if self.options.verbose:
512 print "%-16s %s"%('main specfile:',self.main_specname())
513 print "%-16s %s"%('specfiles:',self.all_specnames())
515 ##############################
517 # print 'verbose',self.options.verbose
518 # print 'list_tags',self.options.list_tags
519 # print 'list_branches',self.options.list_branches
520 # print 'all_modules',self.options.all_modules
522 (verbose,branches,pattern,exact) = (self.options.verbose,self.options.list_branches,
523 self.options.list_pattern,self.options.list_exact)
527 if hasattr(self,'branch'):
531 if verbose: grep="%s/$"%exact
532 else: grep="^%s$"%exact
535 extra_command=" | grep %s"%grep
536 extra_message=" matching %s"%grep
539 message="==================== tags for %s"%self.friendly_name()
541 if verbose: command+="--verbose "
542 command += "%s/tags"%self.mod_url()
543 command += extra_command
544 message += extra_message
545 if verbose: print message
549 message="==================== branches for %s"%self.friendly_name()
551 if verbose: command+="--verbose "
552 command += "%s/branches"%self.mod_url()
553 command += extra_command
554 message += extra_message
555 if verbose: print message
558 ##############################
559 sync_warning="""*** WARNING
560 The module-sync function has the following limitations
561 * it does not handle changelogs
562 * it does not scan the -tags*.mk files to adopt the new tags"""
565 if self.options.verbose:
566 print Module.sync_warning
567 if not prompt('Want to proceed anyway'):
570 self.init_module_dir()
572 self.revert_edge_dir()
573 self.update_edge_dir()
574 spec_dict = self.spec_dict()
576 edge_url=self.edge_url()
577 tag_name=self.tag_name(spec_dict)
578 tag_url=self.tag_url(spec_dict)
579 # check the tag does not exist yet
580 self.check_svnpath_not_exists(tag_url,"new tag")
582 if self.options.message:
583 svnopt='--message "%s"'%self.options.message
585 svnopt='--editor-cmd=%s'%self.options.editor
586 self.run_prompt("Create initial tag",
587 "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
589 ##############################
590 def do_diff (self,compute_only=False):
591 self.init_module_dir()
593 self.revert_edge_dir()
594 self.update_edge_dir()
595 spec_dict = self.spec_dict()
596 self.show_dict(spec_dict)
598 edge_url=self.edge_url()
599 tag_url=self.tag_url(spec_dict)
600 self.check_svnpath_exists(edge_url,"edge track")
601 self.check_svnpath_exists(tag_url,"latest tag")
602 command="svn diff %s %s"%(tag_url,edge_url)
604 if self.options.verbose:
605 print 'Getting diff with %s'%command
606 diff_output = Command(command,self.options).output_of()
607 # if used as a utility
609 return (spec_dict,edge_url,tag_url,diff_output)
610 # otherwise print the result
611 if self.options.list:
615 if not self.options.only or diff_output:
616 print 'x'*30,'module',self.friendly_name()
617 print 'x'*20,'<',tag_url
618 print 'x'*20,'>',edge_url
621 ##############################
622 # using fine_grain means replacing only those instances that currently refer to this tag
623 # otherwise, <module>-SVNPATH is replaced unconditionnally
624 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
625 newtagsfile=tagsfile+".new"
627 new=open(newtagsfile,"w")
630 # fine-grain : replace those lines that refer to oldname
632 if self.options.verbose:
633 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
634 matcher=re.compile("^(.*)%s(.*)"%oldname)
635 for line in tags.readlines():
636 if not matcher.match(line):
639 (begin,end)=matcher.match(line).groups()
640 new.write(begin+newname+end+"\n")
642 # brute-force : change uncommented lines that define <module>-SVNPATH
644 if self.options.verbose:
645 print 'Setting %s-SVNPATH for using %s\n\tin %s .. '%(self.name,newname,tagsfile),
646 pattern="\A\s*%s-SVNPATH\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s/[^\s]+"\
647 %(self.name,self.name)
648 matcher_module=re.compile(pattern)
649 for line in tags.readlines():
650 attempt=matcher_module.match(line)
652 svnpath="%s-SVNPATH"%self.name
653 replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
654 new.write(replacement)
660 os.rename(newtagsfile,tagsfile)
661 if self.options.verbose: print "%d changes"%matches
665 self.init_module_dir()
667 self.revert_edge_dir()
668 self.update_edge_dir()
670 spec_dict = self.spec_dict()
671 self.show_dict(spec_dict)
674 edge_url=self.edge_url()
675 old_tag_name = self.tag_name(spec_dict)
676 old_tag_url=self.tag_url(spec_dict)
677 if (self.options.new_version):
678 # new version set on command line
679 spec_dict[self.module_version_varname] = self.options.new_version
680 spec_dict[self.module_taglevel_varname] = 0
683 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
684 spec_dict[self.module_taglevel_varname] = new_taglevel
687 new_tag_name = self.tag_name(spec_dict)
688 new_tag_url=self.tag_url(spec_dict)
689 self.check_svnpath_exists (edge_url,"edge track")
690 self.check_svnpath_exists (old_tag_url,"previous tag")
691 self.check_svnpath_not_exists (new_tag_url,"new tag")
694 diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
695 self.options).output_of()
696 if len(diff_output) == 0:
697 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
700 # side effect in trunk's specfile
701 self.patch_spec_var(spec_dict)
703 # prepare changelog file
704 # we use the standard subversion magic string (see svn_magic_line)
705 # so we can provide useful information, such as version numbers and diff
707 changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
708 file(changelog,"w").write("""Tagging module %s - %s
711 Please write a changelog for this new tag in the section above
712 """%(self.name,new_tag_name,Module.svn_magic_line))
714 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
715 file(changelog,"a").write('DIFF=========\n' + diff_output)
717 if self.options.debug:
721 self.run("%s %s"%(self.options.editor,changelog))
722 # insert changelog in spec
723 if self.options.changelog:
724 self.insert_changelog (changelog,old_tag_name,new_tag_name)
728 buildname=Module.config['build']
731 if self.options.build_branch:
732 buildname+=":"+self.options.build_branch
733 build = Module(buildname,self.options)
734 build.init_module_dir()
735 build.init_edge_dir()
736 build.revert_edge_dir()
737 build.update_edge_dir()
739 tagsfiles=glob(build.edge_dir()+"/*-tags*.mk")
740 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
743 for (tagsfile,status) in tagsdict.iteritems():
744 basename=os.path.basename(tagsfile)
745 print ".................... Dealing with %s"%basename
746 while tagsdict[tagsfile] == 'todo' :
747 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
748 [ ('y','es'), ('n', 'ext'), ('f','orce'),
749 ('d','iff'), ('r','evert'), ('h','elp') ] ,
752 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
754 print 'Done with %s'%os.path.basename(tagsfile)
755 tagsdict[tagsfile]='done'
757 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
759 self.run("svn diff %s"%tagsfile)
761 self.run("svn revert %s"%tagsfile)
764 print """y: change %(name)s-SVNPATH only if it currently refers to %(old_tag_name)s
765 f: unconditionnally change any line setting %(name)s-SVNPATH to using %(new_tag_name)s
766 d: show current diff for this tag file
767 r: revert that tag file
768 n: move to next file"""%locals()
770 if prompt("Want to review changes on tags files",False):
771 tagsdict = dict ( [ (x, 'todo') for tagsfile in tagsfiles ] )
777 paths += self.edge_dir() + " "
778 paths += build.edge_dir() + " "
779 self.run_prompt("Review module and build","svn diff " + paths)
780 self.run_prompt("Commit module and build","svn commit --file %s %s"%(changelog,paths))
781 self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
783 if self.options.debug:
784 print 'Preserving',changelog
788 ##############################
789 def do_branch (self):
791 # save self.branch if any, as a hint for the new branch
792 # do this before anything else and restore .branch to None,
793 # as this is part of the class's logic
796 new_trunk_name=self.branch
799 # compute diff - a way to initialize the whole stuff
800 # do_diff already does edge_dir initialization
801 # and it checks that edge_url and tag_url exist as well
802 (spec_dict,edge_url,tag_url,diff_listing) = self.do_diff(compute_only=True)
804 # the version name in the trunk becomes the new branch name
805 branch_name = spec_dict[self.module_version_varname]
807 # figure new branch name (the one for the trunk) if not provided on the command line
808 if not new_trunk_name:
809 # heuristic is to assume 'version' is a dot-separated name
810 # we isolate the rightmost part and try incrementing it by 1
811 version=spec_dict[self.module_version_varname]
813 m=re.compile("\A(?P<leftpart>.+)\.(?P<rightmost>[^\.]+)\Z")
814 (leftpart,rightmost)=m.match(version).groups()
815 incremented = int(rightmost)+1
816 new_trunk_name="%s.%d"%(leftpart,incremented)
818 raise Exception, 'Cannot figure next branch name from %s - exiting'%version
820 # record starting point tagname
821 latest_tag_name = self.tag_name(spec_dict)
824 print "Using starting point %s (%s)"%(tag_url,latest_tag_name)
825 print "Creating branch %s & moving trunk to %s"%(branch_name,new_trunk_name)
828 # print warning if pending diffs
830 print """*** WARNING : Module %s has pending diffs on its trunk
831 It is safe to proceed, but please note that branch %s
832 will be based on latest tag %s and *not* on the current trunk"""%(self.name,branch_name,latest_tag_name)
834 answer = prompt ('Are you sure you want to proceed with branching',True,('d','iff'))
837 elif answer is False:
838 raise Exception,"User quit"
840 print '<<<< %s'%tag_url
841 print '>>>> %s'%edge_url
844 branch_url = "%s/%s/branches/%s"%(Module.config['svnpath'],self.name,branch_name)
845 self.check_svnpath_not_exists (branch_url,"new branch")
848 spec_dict[self.module_version_varname]=new_trunk_name
849 spec_dict[self.module_taglevel_varname]='0'
850 # remember this in the trunk for easy location of the current branch
851 spec_dict['module_current_branch']=branch_name
852 self.patch_spec_var(spec_dict,True)
854 # create commit log file
855 tmp="/tmp/branching-%d"%os.getpid()
857 f.write("Branch %s for module %s created (as new trunk) from tag %s\n"%(new_trunk_name,self.name,latest_tag_name))
860 # we're done, let's commit the stuff
861 command="svn diff %s"%self.edge_dir()
862 self.run_prompt("Review changes in trunk",command)
863 command="svn copy --file %s %s %s"%(tmp,self.edge_url(),branch_url)
864 self.run_prompt("Create branch",command)
865 command="svn commit --file %s %s"%(tmp,self.edge_dir())
866 self.run_prompt("Commit trunk",command)
867 new_tag_url=self.tag_url(spec_dict)
868 command="svn copy --file %s %s %s"%(tmp,self.edge_url(),new_tag_url)
869 self.run_prompt("Create initial tag in trunk",command)
872 ##############################
875 def __init__(self, package, module, svnpath, spec):
880 self.specpath="%s/%s"%(svnpath,spec)
881 self.basename=os.path.basename(svnpath)
883 # returns a http URL to the trac path where full diff can be viewed (between self and pkg)
884 # typically http://svn.planet-lab.org/changeset?old_path=Monitor%2Ftags%2FMonitor-1.0-7&new_path=Monitor%2Ftags%2FMonitor-1.0-13
885 # xxx quick & dirty: rough url parsing
886 def trac_full_diff (self, pkg):
887 matcher=re.compile("\A(?P<method>.*)://(?P<hostname>[^/]+)/(svn/)?(?P<path>.*)\Z")
888 self_match=matcher.match(self.svnpath)
889 pkg_match=matcher.match(pkg.svnpath)
890 if self_match and pkg_match:
891 (method,hostname,svn,path)=self_match.groups()
892 self_path=path.replace("/","%2F")
893 pkg_path=pkg_match.group('path').replace("/","%2F")
894 return "%s://%s/changeset?old_path=%s&new_path=%s"%(method,hostname,self_path,pkg_path)
898 class Build (Module):
900 def __init__ (self, buildtag,options):
901 self.buildtag=buildtag
902 Module.__init__(self,"build@%s"%buildtag,options)
904 # we cannot get build's svnpath as for other packages as we'd get something in svn+ssh
906 def get_svnpath (self):
907 self.svnpath="http://svn.planet-lab.org/svn/build/tags/%s"%self.buildtag
909 def get_packages (self,distrotag):
910 # mhh: remove -tag* from distrotags to get distro
911 n=distrotag.find('-tag')
917 make_options="-C %s stage1=true PLDISTRO=%s PLDISTROTAGS=%s 2> /dev/null"%(self.edge_dir(),distro,distrotag)
918 command="make %s packages"%make_options
919 make_packages=Command(command,self.options).output_of()
920 pkg_line=re.compile("\Apackage=(?P<package>[^\s]+)\s+ref_module=(?P<module>[^\s]+)\s.*\Z")
921 for line in make_packages.split("\n"):
924 attempt=pkg_line.match(line)
925 if line and not attempt:
927 print "WARNING: line not understood from make packages"
928 print "in dir %s"%self.edge_dir
929 print "with options",make_options
933 (package,module) = (attempt.group('package'),attempt.group('module'))
934 command="make %s +%s-SVNPATH"%(make_options,module)
935 svnpath=Command(command,self.options).output_of().strip()
936 command="make %s +%s-SPEC"%(make_options,package)
937 spec=Command(command,self.options).output_of().strip()
938 result[package]=Package(package,module,svnpath,spec)
941 def get_distrotags (self):
942 return [os.path.basename(p) for p in glob("%s/*tags*mk"%self.edge_dir())]
947 # header in diff output
948 discard_matcher=re.compile("\A(\+\+\+|---).*")
951 def do_changelog (buildtag_new,buildtag_old,options):
955 print "= build tag %s to %s = #tag-%s"%(buildtag_old,buildtag_new,buildtag_new)
956 (build_new,build_old) = (Build (buildtag_new,options), Build (buildtag_old,options))
957 for b in (build_new,build_old):
962 # find out the tags files that are common, unless option was specified
963 if options.distrotags:
964 (distrotags_new,distrotags_old)=([options.distrotags],[options.distrotags])
966 distrotags_new=build_new.get_distrotags()
967 distrotags_old=build_old.get_distrotags()
968 distrotags = list(set(distrotags_new).intersection(set(distrotags_old)))
971 print "Found distrotags",distrotags
973 for distrotag in distrotags:
975 first_distrotag=False
978 print '== distro %s (%s to %s) == #distro-%s-%s'%(distrotag,buildtag_old,buildtag_new,distrotag,buildtag_new)
979 print ' * from %s/%s'%(build_old.svnpath,distrotag)
980 print ' * to %s/%s'%(build_new.svnpath,distrotag)
982 # parse make packages
983 packages_new=build_new.get_packages(distrotag)
984 pnames_new=set(packages_new.keys())
985 packages_old=build_old.get_packages(distrotag)
986 pnames_old=set(packages_old.keys())
988 # get created, deprecated, and preserved package names
989 pnames_created = list(pnames_new-pnames_old)
990 pnames_created.sort()
991 pnames_deprecated = list(pnames_old-pnames_new)
992 pnames_deprecated.sort()
993 pnames = list(pnames_new.intersection(pnames_old))
997 print "Found new/deprecated/preserved pnames",pnames_new,pnames_deprecated,pnames
999 # display created and deprecated
1000 for name in pnames_created:
1001 print '=== %s : new package %s -- appeared in %s === #pkg-%s-%s'%(distrotag,name,buildtag_new,name,buildtag_new)
1002 obj=packages_new[name]
1003 print ' * svn link: %s'%obj.svnpath
1004 print ' * spec: %s'%obj.specpath
1005 for name in pnames_deprecated:
1006 print '=== %s : package %s -- deprecated, last occurrence in %s === #pkg-%s-%s'%(distrotag,name,buildtag_old,name,buildtag_new)
1007 obj=packages_old[name]
1009 print ' * codebase stored in CVS, specfile is %s'%obj.spec
1011 print ' * svn link: %s'%obj.svnpath
1012 print ' * spec: %s'%obj.specpath
1014 # display other packages
1016 (pobj_new,pobj_old)=(packages_new[name],packages_old[name])
1018 print "Dealing with package",name
1019 if pobj_new.specpath == pobj_old.specpath:
1021 command="svn diff %s %s"%(pobj_old.specpath,pobj_new.specpath)
1022 specdiff=Command(command,options).output_of()
1025 print '=== %s - %s to %s : package %s === #pkg-%s-%s'%(distrotag,buildtag_old,buildtag_new,name,name,buildtag_new)
1026 print ' * from [%s %s] ([%s spec])'%(pobj_old.svnpath,pobj_old.basename,pobj_old.specpath),
1027 print ' to [%s %s] ([%s spec])'%(pobj_new.svnpath,pobj_new.basename,pobj_new.specpath)
1028 trac_diff_url=pobj_old.trac_full_diff(pobj_new)
1030 print ' * [%s View full diff]'%trac_diff_url
1032 for line in specdiff.split('\n'):
1035 if Release.discard_matcher.match(line):
1037 if line[0] in ['@']:
1039 elif line[0] in ['+','-']:
1043 ##############################
1046 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1047 module-tools : a set of tools to manage subversion tags and specfile
1048 requires the specfile to either
1049 * define *version* and *taglevel*
1051 * define redirection variables module_version_varname / module_taglevel_varname
1053 by default, the trunk of modules is taken into account
1054 in this case, just mention the module name as <module_desc>
1056 if you wish to work on a branch rather than on the trunk,
1057 you can use something like e.g. Mom:2.1 as <module_desc>
1059 release_usage="""Usage: %prog [options] tag1 .. tagn
1060 Extract release notes from the changes in specfiles between several build tags, latest first
1062 common_usage="""More help:
1063 see http://svn.planet-lab.org/wiki/ModuleTools"""
1066 'list' : "displays a list of available tags or branches",
1067 'version' : "check latest specfile and print out details",
1068 'diff' : "show difference between module (trunk or branch) and latest tag",
1069 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1070 create new tag and and monitor its adoption in build/*-tags*.mk""",
1071 'branch' : """create a branch for this module, from the latest tag on the trunk,
1072 and change trunk's version number to reflect the new branch name;
1073 you can specify the new branch name by using module:branch""",
1074 'sync' : """create a tag from the module
1075 this is a last resort option, mostly for repairs""",
1076 'changelog' : """extract changelog between build tags
1077 expected arguments are a list of tags""",
1080 silent_modes = ['list']
1081 release_modes = ['changelog']
1086 for function in Main.modes.keys():
1087 if sys.argv[0].find(function) >= 0:
1091 print "Unsupported command",sys.argv[0]
1092 print "Supported commands:" + Modes.modes.keys.join(" ")
1095 if mode not in Main.release_modes:
1096 usage = Main.module_usage
1097 usage += Main.common_usage
1098 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1100 usage = Main.release_usage
1101 usage += Main.common_usage
1103 parser=OptionParser(usage=usage,version=subversion_id)
1106 parser.add_option("-b","--branches",action="store_true",dest="list_branches",default=False,
1107 help="list branches")
1108 parser.add_option("-t","--tags",action="store_false",dest="list_branches",
1110 parser.add_option("-m","--match",action="store",dest="list_pattern",default=None,
1111 help="grep pattern for filtering output")
1112 parser.add_option("-x","--exact-match",action="store",dest="list_exact",default=None,
1113 help="exact grep pattern for filtering output")
1114 if mode == "tag" or mode == 'branch':
1115 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1116 help="set new version and reset taglevel to 0")
1118 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1119 help="do not update changelog section in specfile when tagging")
1120 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1121 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1122 if mode == "tag" or mode == "sync" :
1123 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1124 help="specify editor")
1126 parser.add_option("-m","--message", action="store", dest="message", default=None,
1127 help="specify log message")
1129 parser.add_option("-o","--only", action="store_true", dest="only", default=False,
1130 help="report diff only for modules that exhibit differences")
1132 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1133 help="just list modules that exhibit differences")
1135 if mode == 'version':
1136 parser.add_option("-u","--url", action="store_true", dest="show_urls", default=False,
1137 help="display URLs")
1139 if mode not in Main.release_modes:
1140 all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
1141 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1142 help="run on all modules as found in %s"%all_modules)
1144 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1145 help="dry run - shell commands are only displayed")
1146 parser.add_option("-t","--distrotags",action="store",dest="distrotags",default=None,
1147 help="specify a distro-tags file, e.g. onelab-tags-4.2.mk")
1149 parser.add_option("-w","--workdir", action="store", dest="workdir",
1150 default="%s/%s"%(os.getenv("HOME"),"modules"),
1151 help="""name for dedicated working dir - defaults to ~/modules
1152 ** THIS MUST NOT ** be your usual working directory""")
1153 parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
1154 help="skip safety checks, such as svn updates -- use with care")
1156 # default verbosity depending on function - temp
1157 verbose_modes= ['tag','sync']
1159 if mode not in verbose_modes:
1160 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1161 help="run in verbose mode")
1163 parser.add_parser("-q","--quiet", action="store_false", dest="verbose", default=True,
1164 help="run in quiet (non-verbose) mode")
1165 # parser.add_option("-d","--debug", action="store_true", dest="debug", default=False,
1166 # help="debug mode - mostly more verbose")
1167 (options, args) = parser.parse_args()
1169 if not hasattr(options,'dry_run'):
1170 options.dry_run=False
1173 ########## release-*
1174 if mode in Main.release_modes :
1175 ########## changelog
1179 Module.init_homedir(options)
1180 for n in range(len(args)-1):
1181 [t_new,t_old]=args[n:n+2]
1182 Release.do_changelog (t_new,t_old,options)
1186 if options.all_modules:
1187 args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
1191 Module.init_homedir(options)
1192 for modname in args:
1193 module=Module(modname,options)
1194 if len(args)>1 and mode not in Main.silent_modes:
1195 print '========================================',module.friendly_name()
1196 # call the method called do_<mode>
1197 method=Module.__dict__["do_%s"%mode]
1201 print 'Skipping failed %s: '%modname,e
1203 ####################
1204 if __name__ == "__main__" :
1207 except KeyboardInterrupt: