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 # store and restitute html fragments
237 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
239 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
241 # only the fake error module has multiple titles
242 def html_store_title (self, title):
243 if not hasattr(self,'titles'): self.titles=[]
244 self.titles.append(title)
245 def html_store_raw (self, html):
246 if not hasattr(self,'body'): self.body=''
248 def html_store_pre (self, text):
249 if not hasattr(self,'body'): self.body=''
250 self.body += '<pre>' + text + '</pre>'
252 def html_dump_header(self):
253 now=time.strftime("%Y-%m-%d %H:%M")
255 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
256 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
258 <title> Pending changes in %s </title>
259 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
260 <style type="text/css">
261 body { font-family:georgia, serif; }
262 h1 {font-size: large; }
263 p.title {font-size: x-large; }
264 span.error {text-weight:bold; color: red; }
268 <p class='title'> Pending changes in %s - status at %s</p>
270 """%(self.options.www,self.options.www,now)
273 def html_dump_middle():
277 def html_dump_footer():
278 print "</body></html"
280 def html_dump_toc(self):
281 if hasattr(self,'titles'):
282 for title in self.titles:
283 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
285 def html_dump_body(self):
286 if hasattr(self,'titles'):
287 for title in self.titles:
289 print '<h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
290 if hasattr(self,'body'):
295 def init_homedir (options):
296 topdir=options.workdir
297 if options.verbose and options.mode not in Main.silent_modes:
298 print 'Checking for',topdir
299 storage="%s/%s"%(topdir,Module.config_storage)
300 # sanity check. Either the topdir exists AND we have a config/storage
301 # or topdir does not exist and we create it
302 # to avoid people use their own daily svn repo
303 if os.path.isdir(topdir) and not os.path.isfile(storage):
304 print """The directory %s exists and has no CONFIG file
305 If this is your regular working directory, please provide another one as the
306 module-* commands need a fresh working dir. Make sure that you do not use
307 that for other purposes than tagging"""%topdir
309 if not os.path.isdir (topdir):
310 print "Cannot find",topdir,"let's create it"
311 Module.prompt_config()
312 print "Checking ...",
313 Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
314 Command("svn co -N %s/%s %s/%s"%(Module.config['svnpath'],
315 Module.config['build'],
317 Module.config['build']),options).run_fatal()
322 for (key,message,default) in Module.configKeys:
323 f.write("%s=%s\n"%(key,Module.config[key]))
326 print 'Stored',storage
327 Command("cat %s"%storage,options).run()
331 for line in f.readlines():
332 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
333 Module.config[key]=value
335 if options.verbose and options.mode not in Main.silent_modes:
336 print '******** Using config'
337 for (key,message,default) in Module.configKeys:
338 print '\t',key,'=',Module.config[key]
340 def init_module_dir (self):
341 if self.options.verbose:
342 print 'Checking for',self.module_dir
343 if not os.path.isdir (self.module_dir):
344 self.run_fatal("svn update -N %s"%self.module_dir)
345 if not os.path.isdir (self.module_dir):
346 raise Exception, 'Cannot find %s - check module name'%self.module_dir
348 def init_subdir (self,fullpath):
349 if self.options.verbose:
350 print 'Checking for',fullpath
351 if not os.path.isdir (fullpath):
352 self.run_fatal("svn update -N %s"%fullpath)
354 def revert_subdir (self,fullpath):
355 if self.options.fast_checks:
356 if self.options.verbose: print 'Skipping revert of %s'%fullpath
358 if self.options.verbose:
359 print 'Checking whether',fullpath,'needs being reverted'
360 if Svnpath(fullpath,self.options).dir_needs_revert():
361 self.run_fatal("svn revert -R %s"%fullpath)
363 def update_subdir (self,fullpath):
364 if self.options.fast_checks:
365 if self.options.verbose: print 'Skipping update of %s'%fullpath
367 if self.options.verbose:
368 print 'Updating',fullpath
369 self.run_fatal("svn update -N %s"%fullpath)
371 def init_edge_dir (self):
372 # if branch, edge_dir is two steps down
373 if hasattr(self,'branch'):
374 self.init_subdir("%s/branches"%self.module_dir)
375 elif hasattr(self,'tagname'):
376 self.init_subdir("%s/tags"%self.module_dir)
377 self.init_subdir(self.edge_dir())
379 def revert_edge_dir (self):
380 self.revert_subdir(self.edge_dir())
382 def update_edge_dir (self):
383 self.update_subdir(self.edge_dir())
385 def main_specname (self):
386 attempt="%s/%s.spec"%(self.edge_dir(),self.name)
387 if os.path.isfile (attempt):
390 pattern="%s/*.spec"%self.edge_dir()
392 return glob(pattern)[0]
394 raise Exception, 'Cannot guess specfile for module %s -- pattern was %s'%(self.name,pattern)
396 def all_specnames (self):
397 return glob("%s/*.spec"%self.edge_dir())
399 def parse_spec (self, specfile, varnames):
400 if self.options.verbose:
401 print 'Parsing',specfile,
407 for line in f.readlines():
408 attempt=Module.matcher_rpm_define.match(line)
410 (define,var,value)=attempt.groups()
414 if self.options.debug:
415 print 'found',len(result),'keys'
416 for (k,v) in result.iteritems():
420 # stores in self.module_name_varname the rpm variable to be used for the module's name
421 # and the list of these names in self.varnames
422 def spec_dict (self):
423 specfile=self.main_specname()
424 redirector_keys = [ varname for (varname,default) in Module.redirectors]
425 redirect_dict = self.parse_spec(specfile,redirector_keys)
426 if self.options.debug:
427 print '1st pass parsing done, redirect_dict=',redirect_dict
429 for (varname,default) in Module.redirectors:
430 if redirect_dict.has_key(varname):
431 setattr(self,varname,redirect_dict[varname])
432 varnames += [redirect_dict[varname]]
434 setattr(self,varname,default)
435 varnames += [ default ]
436 self.varnames = varnames
437 result = self.parse_spec (specfile,self.varnames)
438 if self.options.debug:
439 print '2st pass parsing done, varnames=',varnames,'result=',result
442 def patch_spec_var (self, patch_dict,define_missing=False):
443 for specfile in self.all_specnames():
444 # record the keys that were changed
445 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
446 newspecfile=specfile+".new"
447 if self.options.verbose:
448 print 'Patching',specfile,'for',patch_dict.keys()
450 new=open(newspecfile,"w")
452 for line in spec.readlines():
453 attempt=Module.matcher_rpm_define.match(line)
455 (define,var,value)=attempt.groups()
456 if var in patch_dict.keys():
457 if self.options.debug:
458 print 'rewriting %s as %s'%(var,patch_dict[var])
459 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
464 for (key,was_changed) in changed.iteritems():
466 if self.options.debug:
467 print 'rewriting missing %s as %s'%(key,patch_dict[key])
468 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
471 os.rename(newspecfile,specfile)
473 def unignored_lines (self, logfile):
475 exclude="Setting tag %s"%self.name
476 white_line_matcher = re.compile("\A\s*\Z")
477 for logline in file(logfile).readlines():
478 if logline.strip() == Module.svn_magic_line:
480 if logline.find(exclude) >= 0:
482 elif white_line_matcher.match(logline):
485 result.append(logline.strip()+'\n')
488 def insert_changelog (self, logfile, oldtag, newtag):
489 for specfile in self.all_specnames():
490 newspecfile=specfile+".new"
491 if self.options.verbose:
492 print 'Inserting changelog from %s into %s'%(logfile,specfile)
494 new=open(newspecfile,"w")
495 for line in spec.readlines():
497 if re.compile('%changelog').match(line):
498 dateformat="* %a %b %d %Y"
499 datepart=time.strftime(dateformat)
500 logpart="%s <%s> - %s"%(Module.config['username'],
501 Module.config['email'],
503 new.write(datepart+" "+logpart+"\n")
504 for logline in self.unignored_lines(logfile):
505 new.write("- " + logline)
509 os.rename(newspecfile,specfile)
511 def show_dict (self, spec_dict):
512 if self.options.verbose:
513 for (k,v) in spec_dict.iteritems():
517 return "%s/%s"%(Module.config['svnpath'],self.name)
520 if hasattr(self,'branch'):
521 return "%s/branches/%s"%(self.mod_url(),self.branch)
522 elif hasattr(self,'tagname'):
523 return "%s/tags/%s"%(self.mod_url(),self.tagname)
525 return "%s/trunk"%(self.mod_url())
527 def tag_name (self, spec_dict):
529 return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
531 spec_dict[self.module_version_varname],
532 spec_dict[self.module_taglevel_varname])
534 raise Exception, 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
536 def tag_url (self, spec_dict):
537 return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
539 def check_svnpath_exists (self, url, message):
540 if self.options.fast_checks:
542 if self.options.verbose:
543 print 'Checking url (%s) %s'%(url,message),
544 ok=Svnpath(url,self.options).url_exists()
546 if self.options.verbose: print 'exists - OK'
548 if self.options.verbose: print 'KO'
549 raise Exception, 'Could not find %s URL %s'%(message,url)
551 def check_svnpath_not_exists (self, url, message):
552 if self.options.fast_checks:
554 if self.options.verbose:
555 print 'Checking url (%s) %s'%(url,message),
556 ok=not Svnpath(url,self.options).url_exists()
558 if self.options.verbose: print 'does not exist - OK'
560 if self.options.verbose: print 'KO'
561 raise Exception, '%s URL %s already exists - exiting'%(message,url)
563 # locate specfile, parse it, check it and show values
565 ##############################
566 def do_version (self):
567 self.init_module_dir()
569 self.revert_edge_dir()
570 self.update_edge_dir()
571 spec_dict = self.spec_dict()
572 for varname in self.varnames:
573 if not spec_dict.has_key(varname):
574 print 'Could not find %%define for %s'%varname
577 print "%-16s %s"%(varname,spec_dict[varname])
578 if self.options.show_urls:
579 print "%-16s %s"%('edge url',self.edge_url())
580 print "%-16s %s"%('latest tag url',self.tag_url(spec_dict))
581 if self.options.verbose:
582 print "%-16s %s"%('main specfile:',self.main_specname())
583 print "%-16s %s"%('specfiles:',self.all_specnames())
585 ##############################
587 # print 'verbose',self.options.verbose
588 # print 'list_tags',self.options.list_tags
589 # print 'list_branches',self.options.list_branches
590 # print 'all_modules',self.options.all_modules
592 (verbose,branches,pattern,exact) = (self.options.verbose,self.options.list_branches,
593 self.options.list_pattern,self.options.list_exact)
597 if hasattr(self,'branch'):
601 if verbose: grep="%s/$"%exact
602 else: grep="^%s$"%exact
605 extra_command=" | grep %s"%grep
606 extra_message=" matching %s"%grep
609 message="==================== tags for %s"%self.friendly_name()
611 if verbose: command+="--verbose "
612 command += "%s/tags"%self.mod_url()
613 command += extra_command
614 message += extra_message
615 if verbose: print message
619 message="==================== branches for %s"%self.friendly_name()
621 if verbose: command+="--verbose "
622 command += "%s/branches"%self.mod_url()
623 command += extra_command
624 message += extra_message
625 if verbose: print message
628 ##############################
629 sync_warning="""*** WARNING
630 The module-sync function has the following limitations
631 * it does not handle changelogs
632 * it does not scan the -tags*.mk files to adopt the new tags"""
635 if self.options.verbose:
636 print Module.sync_warning
637 if not prompt('Want to proceed anyway'):
640 self.init_module_dir()
642 self.revert_edge_dir()
643 self.update_edge_dir()
644 spec_dict = self.spec_dict()
646 edge_url=self.edge_url()
647 tag_name=self.tag_name(spec_dict)
648 tag_url=self.tag_url(spec_dict)
649 # check the tag does not exist yet
650 self.check_svnpath_not_exists(tag_url,"new tag")
652 if self.options.message:
653 svnopt='--message "%s"'%self.options.message
655 svnopt='--editor-cmd=%s'%self.options.editor
656 self.run_prompt("Create initial tag",
657 "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
659 ##############################
660 def do_diff (self,compute_only=False):
661 self.init_module_dir()
663 self.revert_edge_dir()
664 self.update_edge_dir()
665 spec_dict = self.spec_dict()
666 self.show_dict(spec_dict)
668 edge_url=self.edge_url()
669 tag_url=self.tag_url(spec_dict)
670 self.check_svnpath_exists(edge_url,"edge track")
671 self.check_svnpath_exists(tag_url,"latest tag")
672 command="svn diff %s %s"%(tag_url,edge_url)
674 if self.options.verbose:
675 print 'Getting diff with %s'%command
676 diff_output = Command(command,self.options).output_of()
677 # if used as a utility
679 return (spec_dict,edge_url,tag_url,diff_output)
680 # otherwise print the result
681 if self.options.list:
685 anchor=self.friendly_name()
687 if self.options.www and diff_output:
688 self.html_store_title("Diffs in module %s (%d chars)"%(anchor,len(diff_output)))
689 link=self.html_href(tag_url,tag_url)
690 self.html_store_raw ('<p> < (left) %s </p>'%link)
691 link=self.html_href(edge_url,edge_url)
692 self.html_store_raw ('<p> > (right) %s </p>'%link)
693 self.html_store_pre (diff_output)
694 elif not self.options.www:
695 print 'x'*30,'module',anchor
696 print 'x'*20,'<',tag_url
697 print 'x'*20,'>',edge_url
700 ##############################
701 # using fine_grain means replacing only those instances that currently refer to this tag
702 # otherwise, <module>-SVNPATH is replaced unconditionnally
703 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
704 newtagsfile=tagsfile+".new"
706 new=open(newtagsfile,"w")
709 # fine-grain : replace those lines that refer to oldname
711 if self.options.verbose:
712 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
713 matcher=re.compile("^(.*)%s(.*)"%oldname)
714 for line in tags.readlines():
715 if not matcher.match(line):
718 (begin,end)=matcher.match(line).groups()
719 new.write(begin+newname+end+"\n")
721 # brute-force : change uncommented lines that define <module>-SVNPATH
723 if self.options.verbose:
724 print 'Searching for -SVNPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
725 pattern="\A\s*(?P<make_name>[^\s]+)-SVNPATH\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s/[^\s]+"\
727 matcher_module=re.compile(pattern)
728 for line in tags.readlines():
729 attempt=matcher_module.match(line)
731 svnpath="%s-SVNPATH"%(attempt.group('make_name'))
732 if self.options.verbose:
734 replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
735 new.write(replacement)
741 os.rename(newtagsfile,tagsfile)
742 if self.options.verbose: print "%d changes"%matches
746 self.init_module_dir()
748 self.revert_edge_dir()
749 self.update_edge_dir()
751 spec_dict = self.spec_dict()
752 self.show_dict(spec_dict)
755 edge_url=self.edge_url()
756 old_tag_name = self.tag_name(spec_dict)
757 old_tag_url=self.tag_url(spec_dict)
758 if (self.options.new_version):
759 # new version set on command line
760 spec_dict[self.module_version_varname] = self.options.new_version
761 spec_dict[self.module_taglevel_varname] = 0
764 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
765 spec_dict[self.module_taglevel_varname] = new_taglevel
768 new_tag_name = self.tag_name(spec_dict)
769 new_tag_url=self.tag_url(spec_dict)
770 self.check_svnpath_exists (edge_url,"edge track")
771 self.check_svnpath_exists (old_tag_url,"previous tag")
772 self.check_svnpath_not_exists (new_tag_url,"new tag")
775 diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
776 self.options).output_of()
777 if len(diff_output) == 0:
778 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
781 # side effect in trunk's specfile
782 self.patch_spec_var(spec_dict)
784 # prepare changelog file
785 # we use the standard subversion magic string (see svn_magic_line)
786 # so we can provide useful information, such as version numbers and diff
788 changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
789 file(changelog,"w").write("""Setting tag %s
792 Please write a changelog for this new tag in the section above
793 """%(new_tag_name,Module.svn_magic_line))
795 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
796 file(changelog,"a").write('DIFF=========\n' + diff_output)
798 if self.options.debug:
802 self.run("%s %s"%(self.options.editor,changelog))
803 # insert changelog in spec
804 if self.options.changelog:
805 self.insert_changelog (changelog,old_tag_name,new_tag_name)
809 buildname=Module.config['build']
812 if self.options.build_branch:
813 buildname+=":"+self.options.build_branch
814 build = Module(buildname,self.options)
815 build.init_module_dir()
816 build.init_edge_dir()
817 build.revert_edge_dir()
818 build.update_edge_dir()
820 tagsfiles=glob(build.edge_dir()+"/*-tags*.mk")
821 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
824 for (tagsfile,status) in tagsdict.iteritems():
825 basename=os.path.basename(tagsfile)
826 print ".................... Dealing with %s"%basename
827 while tagsdict[tagsfile] == 'todo' :
828 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
829 [ ('y','es'), ('n', 'ext'), ('f','orce'),
830 ('d','iff'), ('r','evert'), ('h','elp') ] ,
833 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
835 print 'Done with %s'%os.path.basename(tagsfile)
836 tagsdict[tagsfile]='done'
838 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
840 self.run("svn diff %s"%tagsfile)
842 self.run("svn revert %s"%tagsfile)
845 print """y: change %(name)s-SVNPATH only if it currently refers to %(old_tag_name)s
846 f: unconditionnally change any line setting %(name)s-SVNPATH to using %(new_tag_name)s
847 d: show current diff for this tag file
848 r: revert that tag file
849 n: move to next file"""%locals()
851 if prompt("Want to review changes on tags files",False):
852 tagsdict = dict ( [ (x, 'todo') for tagsfile in tagsfiles ] )
858 paths += self.edge_dir() + " "
859 paths += build.edge_dir() + " "
860 self.run_prompt("Review module and build","svn diff " + paths)
861 self.run_prompt("Commit module and build","svn commit --file %s %s"%(changelog,paths))
862 self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
864 if self.options.debug:
865 print 'Preserving',changelog
869 ##############################
870 def do_branch (self):
872 # save self.branch if any, as a hint for the new branch
873 # do this before anything else and restore .branch to None,
874 # as this is part of the class's logic
876 if hasattr(self,'branch'):
877 new_trunk_name=self.branch
879 elif self.options.new_version:
880 new_trunk_name = self.options.new_version
882 # compute diff - a way to initialize the whole stuff
883 # do_diff already does edge_dir initialization
884 # and it checks that edge_url and tag_url exist as well
885 (spec_dict,edge_url,tag_url,diff_listing) = self.do_diff(compute_only=True)
887 # the version name in the trunk becomes the new branch name
888 branch_name = spec_dict[self.module_version_varname]
890 # figure new branch name (the one for the trunk) if not provided on the command line
891 if not new_trunk_name:
892 # heuristic is to assume 'version' is a dot-separated name
893 # we isolate the rightmost part and try incrementing it by 1
894 version=spec_dict[self.module_version_varname]
896 m=re.compile("\A(?P<leftpart>.+)\.(?P<rightmost>[^\.]+)\Z")
897 (leftpart,rightmost)=m.match(version).groups()
898 incremented = int(rightmost)+1
899 new_trunk_name="%s.%d"%(leftpart,incremented)
901 raise Exception, 'Cannot figure next branch name from %s - exiting'%version
903 # record starting point tagname
904 latest_tag_name = self.tag_name(spec_dict)
907 print "Using starting point %s (%s)"%(tag_url,latest_tag_name)
908 print "Creating branch %s & moving trunk to %s"%(branch_name,new_trunk_name)
911 # print warning if pending diffs
913 print """*** WARNING : Module %s has pending diffs on its trunk
914 It is safe to proceed, but please note that branch %s
915 will be based on latest tag %s and *not* on the current trunk"""%(self.name,branch_name,latest_tag_name)
917 answer = prompt ('Are you sure you want to proceed with branching',True,('d','iff'))
920 elif answer is False:
921 raise Exception,"User quit"
923 print '<<<< %s'%tag_url
924 print '>>>> %s'%edge_url
927 branch_url = "%s/%s/branches/%s"%(Module.config['svnpath'],self.name,branch_name)
928 self.check_svnpath_not_exists (branch_url,"new branch")
931 spec_dict[self.module_version_varname]=new_trunk_name
932 spec_dict[self.module_taglevel_varname]='0'
933 # remember this in the trunk for easy location of the current branch
934 spec_dict['module_current_branch']=branch_name
935 self.patch_spec_var(spec_dict,True)
937 # create commit log file
938 tmp="/tmp/branching-%d"%os.getpid()
940 f.write("Branch %s for module %s created (as new trunk) from tag %s\n"%(new_trunk_name,self.name,latest_tag_name))
943 # we're done, let's commit the stuff
944 command="svn diff %s"%self.edge_dir()
945 self.run_prompt("Review changes in trunk",command)
946 command="svn copy --file %s %s %s"%(tmp,self.edge_url(),branch_url)
947 self.run_prompt("Create branch",command)
948 command="svn commit --file %s %s"%(tmp,self.edge_dir())
949 self.run_prompt("Commit trunk",command)
950 new_tag_url=self.tag_url(spec_dict)
951 command="svn copy --file %s %s %s"%(tmp,self.edge_url(),new_tag_url)
952 self.run_prompt("Create initial tag in trunk",command)
955 ##############################
958 def __init__(self, package, module, svnpath, spec):
963 self.specpath="%s/%s"%(svnpath,spec)
964 self.basename=os.path.basename(svnpath)
966 # returns a http URL to the trac path where full diff can be viewed (between self and pkg)
967 # typically http://svn.planet-lab.org/changeset?old_path=Monitor%2Ftags%2FMonitor-1.0-7&new_path=Monitor%2Ftags%2FMonitor-1.0-13
968 # xxx quick & dirty: rough url parsing
969 def trac_full_diff (self, pkg):
970 matcher=re.compile("\A(?P<method>.*)://(?P<hostname>[^/]+)/(svn/)?(?P<path>.*)\Z")
971 self_match=matcher.match(self.svnpath)
972 pkg_match=matcher.match(pkg.svnpath)
973 if self_match and pkg_match:
974 (method,hostname,svn,path)=self_match.groups()
975 self_path=path.replace("/","%2F")
976 pkg_path=pkg_match.group('path').replace("/","%2F")
977 return "%s://%s/changeset?old_path=%s&new_path=%s"%(method,hostname,self_path,pkg_path)
982 return "[%s %s] [%s (spec)]"%(self.svnpath,self.basename,self.specpath)
984 class Build (Module):
986 # we cannot get build's svnpath as for other packages as we'd get something in svn+ssh
988 def __init__ (self, buildtag,options):
989 self.buildtag=buildtag
990 # if the buildtag start with a : (to use a branch rather than a tag)
991 if buildtag.find(':') == 0 :
992 module_name="build%(buildtag)s"%locals()
993 self.display=buildtag[1:]
994 self.svnpath="http://svn.planet-lab.org/svn/build/branches/%s"%self.display
996 module_name="build@%(buildtag)s"%locals()
997 self.display=buildtag
998 self.svnpath="http://svn.planet-lab.org/svn/build/tags/%s"%self.buildtag
999 Module.__init__(self,module_name,options)
1002 def get_distro_from_distrotag (distrotag):
1003 # mhh: remove -tag* from distrotags to get distro
1004 n=distrotag.find('-tag')
1006 return distrotag[:n]
1010 def get_packages (self,distrotag):
1012 distro=Build.get_distro_from_distrotag(distrotag)
1015 make_options="--no-print-directory -C %s stage1=true PLDISTRO=%s PLDISTROTAGS=%s 2> /dev/null"%(self.edge_dir(),distro,distrotag)
1016 command="make %s packages"%make_options
1017 make_packages=Command(command,self.options).output_of()
1018 pkg_line=re.compile("\Apackage=(?P<package>[^\s]+)\s+ref_module=(?P<module>[^\s]+)\s.*\Z")
1019 for line in make_packages.split("\n"):
1022 attempt=pkg_line.match(line)
1023 if line and not attempt:
1025 print "WARNING: line not understood from make packages"
1026 print "in dir %s"%self.edge_dir
1027 print "with options",make_options
1031 (package,module) = (attempt.group('package'),attempt.group('module'))
1032 command="make %s +%s-SVNPATH"%(make_options,module)
1033 svnpath=Command(command,self.options).output_of().strip()
1034 command="make %s +%s-SPEC"%(make_options,package)
1035 spec=Command(command,self.options).output_of().strip()
1036 result[package]=Package(package,module,svnpath,spec)
1039 def get_distrotags (self):
1040 return [os.path.basename(p) for p in glob("%s/*tags*mk"%self.edge_dir())]
1044 def __init__ (self):
1047 def key(self, frompath,topath):
1048 return frompath+'-to-'+topath
1050 def fetch (self, frompath, topath):
1051 key=self.key(frompath,topath)
1052 if not self._cache.has_key(key):
1054 return self._cache[key]
1056 def store (self, frompath, topath, diff):
1057 key=self.key(frompath,topath)
1058 self._cache[key]=diff
1062 # header in diff output
1063 discard_matcher=re.compile("\A(\+\+\+|---).*")
1066 def do_changelog (buildtag_new,buildtag_old,options):
1070 (build_new,build_old) = (Build (buildtag_new,options), Build (buildtag_old,options))
1071 print "= build tag %s to %s = #build-%s"%(build_old.display,build_new.display,build_new.display)
1072 for b in (build_new,build_old):
1076 # find out the tags files that are common, unless option was specified
1077 if options.distrotags:
1078 distrotags=options.distrotags
1080 distrotags_new=build_new.get_distrotags()
1081 distrotags_old=build_old.get_distrotags()
1082 distrotags = list(set(distrotags_new).intersection(set(distrotags_old)))
1084 if options.verbose: print "Found distrotags",distrotags
1085 first_distrotag=True
1086 diffcache = DiffCache()
1087 for distrotag in distrotags:
1088 distro=Build.get_distro_from_distrotag(distrotag)
1092 first_distrotag=False
1095 print '== distro %s (%s to %s) == #distro-%s-%s'%(distrotag,build_old.display,build_new.display,distro,build_new.display)
1096 print ' * from %s/%s'%(build_old.svnpath,distrotag)
1097 print ' * to %s/%s'%(build_new.svnpath,distrotag)
1099 # parse make packages
1100 packages_new=build_new.get_packages(distrotag)
1101 pnames_new=set(packages_new.keys())
1102 if options.verbose: print 'got packages for ',build_new.display
1103 packages_old=build_old.get_packages(distrotag)
1104 pnames_old=set(packages_old.keys())
1105 if options.verbose: print 'got packages for ',build_old.display
1107 # get created, deprecated, and preserved package names
1108 pnames_created = list(pnames_new-pnames_old)
1109 pnames_created.sort()
1110 pnames_deprecated = list(pnames_old-pnames_new)
1111 pnames_deprecated.sort()
1112 pnames = list(pnames_new.intersection(pnames_old))
1115 if options.verbose: print "Found new/deprecated/preserved pnames",pnames_new,pnames_deprecated,pnames
1117 # display created and deprecated
1118 for name in pnames_created:
1119 print '=== %s : new package %s -- appeared in %s === #package-%s-%s-%s'%(
1120 distrotag,name,build_new.display,name,distro,build_new.display)
1121 pobj=packages_new[name]
1122 print ' * %s'%pobj.details()
1123 for name in pnames_deprecated:
1124 print '=== %s : package %s -- deprecated, last occurrence in %s === #package-%s-%s-%s'%(
1125 distrotag,name,build_old.display,name,distro,build_new.display)
1126 pobj=packages_old[name]
1127 if not pobj.svnpath:
1128 print ' * codebase stored in CVS, specfile is %s'%pobj.spec
1130 print ' * %s'%pobj.details()
1132 # display other packages
1134 (pobj_new,pobj_old)=(packages_new[name],packages_old[name])
1135 if options.verbose: print "Dealing with package",name
1136 if pobj_old.specpath == pobj_new.specpath:
1138 specdiff = diffcache.fetch(pobj_old.specpath,pobj_new.specpath)
1139 if specdiff is None:
1140 command="svn diff %s %s"%(pobj_old.specpath,pobj_new.specpath)
1141 specdiff=Command(command,options).output_of()
1142 diffcache.store(pobj_old.specpath,pobj_new.specpath,specdiff)
1144 if options.verbose: print 'got diff from cache'
1147 print '=== %s - %s to %s : package %s === #package-%s-%s-%s'%(
1148 distrotag,build_old.display,build_new.display,name,name,distro,build_new.display)
1149 print ' * from %s to %s'%(pobj_old.details(),pobj_new.details())
1150 trac_diff_url=pobj_old.trac_full_diff(pobj_new)
1152 print ' * [%s View full diff]'%trac_diff_url
1154 for line in specdiff.split('\n'):
1157 if Release.discard_matcher.match(line):
1159 if line[0] in ['@']:
1161 elif line[0] in ['+','-']:
1165 ##############################
1168 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1169 module-tools : a set of tools to manage subversion tags and specfile
1170 requires the specfile to either
1171 * define *version* and *taglevel*
1173 * define redirection variables module_version_varname / module_taglevel_varname
1175 by default, the trunk of modules is taken into account
1176 in this case, just mention the module name as <module_desc>
1178 if you wish to work on a branch rather than on the trunk,
1179 you can use something like e.g. Mom:2.1 as <module_desc>
1181 release_usage="""Usage: %prog [options] tag1 .. tagn
1182 Extract release notes from the changes in specfiles between several build tags, latest first
1184 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1185 You can refer to a (build) branch by prepending a colon, like in
1186 release-changelog :4.2 4.2-rc25
1188 common_usage="""More help:
1189 see http://svn.planet-lab.org/wiki/ModuleTools"""
1192 'list' : "displays a list of available tags or branches",
1193 'version' : "check latest specfile and print out details",
1194 'diff' : "show difference between module (trunk or branch) and latest tag",
1195 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1196 create new tag and and monitor its adoption in build/*-tags*.mk""",
1197 'branch' : """create a branch for this module, from the latest tag on the trunk,
1198 and change trunk's version number to reflect the new branch name;
1199 you can specify the new branch name by using module:branch""",
1200 'sync' : """create a tag from the module
1201 this is a last resort option, mostly for repairs""",
1202 'changelog' : """extract changelog between build tags
1203 expected arguments are a list of tags""",
1206 silent_modes = ['list']
1207 release_modes = ['changelog']
1210 def optparse_list (option, opt, value, parser):
1212 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1214 setattr(parser.values,option.dest,value.split())
1219 for function in Main.modes.keys():
1220 if sys.argv[0].find(function) >= 0:
1224 print "Unsupported command",sys.argv[0]
1225 print "Supported commands:" + Modes.modes.keys.join(" ")
1228 if mode not in Main.release_modes:
1229 usage = Main.module_usage
1230 usage += Main.common_usage
1231 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1233 usage = Main.release_usage
1234 usage += Main.common_usage
1236 parser=OptionParser(usage=usage,version=subversion_id)
1239 parser.add_option("-b","--branches",action="store_true",dest="list_branches",default=False,
1240 help="list branches")
1241 parser.add_option("-t","--tags",action="store_false",dest="list_branches",
1243 parser.add_option("-m","--match",action="store",dest="list_pattern",default=None,
1244 help="grep pattern for filtering output")
1245 parser.add_option("-x","--exact-match",action="store",dest="list_exact",default=None,
1246 help="exact grep pattern for filtering output")
1247 if mode == "tag" or mode == 'branch':
1248 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1249 help="set new version and reset taglevel to 0")
1251 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1252 help="do not update changelog section in specfile when tagging")
1253 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1254 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1255 if mode == "tag" or mode == "sync" :
1256 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1257 help="specify editor")
1259 parser.add_option("-m","--message", action="store", dest="message", default=None,
1260 help="specify log message")
1262 parser.add_option("-W","--www", action="store", dest="www", default=False,
1263 help="export diff in html format, e.g. -W trunk")
1265 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1266 help="just list modules that exhibit differences")
1268 if mode == 'version':
1269 parser.add_option("-u","--url", action="store_true", dest="show_urls", default=False,
1270 help="display URLs")
1272 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1273 if mode not in Main.release_modes:
1274 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1275 help="run on all modules as found in %s"%default_modules_list)
1276 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1277 help="run on all modules found in specified file")
1279 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1280 help="dry run - shell commands are only displayed")
1281 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1282 default=[], nargs=1,type="string",
1283 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1284 -- can be set multiple times, or use quotes""")
1286 parser.add_option("-w","--workdir", action="store", dest="workdir",
1287 default="%s/%s"%(os.getenv("HOME"),"modules"),
1288 help="""name for dedicated working dir - defaults to ~/modules
1289 ** THIS MUST NOT ** be your usual working directory""")
1290 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1291 help="skip safety checks, such as svn updates -- use with care")
1293 # default verbosity depending on function - temp
1294 verbose_modes= ['tag','sync']
1296 if mode not in verbose_modes:
1297 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1298 help="run in verbose mode")
1300 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1301 help="run in quiet (non-verbose) mode")
1302 # parser.add_option("-d","--debug", action="store_true", dest="debug", default=False,
1303 # help="debug mode - mostly more verbose")
1304 (options, args) = parser.parse_args()
1306 if not hasattr(options,'dry_run'):
1307 options.dry_run=False
1308 if not hasattr(options,'www'):
1312 ########## release-*
1313 if mode in Main.release_modes :
1314 ########## changelog
1318 Module.init_homedir(options)
1319 for n in range(len(args)-1):
1320 [t_new,t_old]=args[n:n+2]
1321 Release.do_changelog (t_new,t_old,options)
1325 if options.all_modules:
1326 options.modules_list=default_modules_list
1327 if options.modules_list:
1328 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1332 Module.init_homedir(options)
1334 # 2 passes for www output
1335 modules=[ Module(modname,options) for modname in args ]
1336 # hack: create a dummy Module to store errors/warnings
1337 error_module = Module('__errors__',options)
1339 # pass 1 : do it, except if options.www
1340 for module in modules:
1341 if len(args)>1 and mode not in Main.silent_modes and not options.www:
1342 print '========================================',module.friendly_name()
1343 # call the method called do_<mode>
1344 method=Module.__dict__["do_%s"%mode]
1349 title='<span class="error"> Skipping module %s - failure: %s </span>'%(module.name, str(e))
1350 error_module.html_store_title(title)
1352 print 'Skipping module %s: '%modname,e
1354 # in which case we do the actual printing in the second pass
1356 modules.append(error_module)
1357 error_module.html_dump_header()
1358 for module in modules:
1359 module.html_dump_toc()
1360 Module.html_dump_middle()
1361 for module in modules:
1362 module.html_dump_body()
1363 Module.html_dump_footer()
1365 ####################
1366 if __name__ == "__main__" :
1369 except KeyboardInterrupt: