7 from optparse import OptionParser
9 # HARDCODED NAME CHANGES
11 # Moving to git we decided to rename some of the repositories. Here is
12 # a map of name changes applied in git repositories.
13 RENAMED_SVN_MODULES = {
17 def svn_to_git_name(module):
18 if RENAMED_SVN_MODULES.has_key(module):
19 return RENAMED_SVN_MODULES[module]
22 def git_to_svn_name(module):
23 for key in RENAMED_SVN_MODULES:
24 if module == RENAMED_SVN_MODULES[key]:
29 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
30 def prompt (question,default=True,other_choices=[],allow_outside=False):
31 if not isinstance (other_choices,list):
32 other_choices = [ other_choices ]
33 chars = [ c for (c,rest) in other_choices ]
37 if default is True: choices.append('[y]')
38 else : choices.append('y')
40 if default is False: choices.append('[n]')
41 else : choices.append('n')
43 for (char,choice) in other_choices:
45 choices.append("["+char+"]"+choice)
47 choices.append("<"+char+">"+choice)
49 answer=raw_input(question + " " + "/".join(choices) + " ? ")
52 answer=answer[0].lower()
54 if 'y' in chars: return 'y'
57 if 'n' in chars: return 'n'
60 for (char,choice) in other_choices:
65 return prompt(question,default,other_choices)
71 editor = os.environ['EDITOR']
79 def print_fold (line):
80 while len(line) >= fold_length:
81 print line[:fold_length],'\\'
82 line=line[fold_length:]
86 def __init__ (self,command,options):
89 self.tmp="/tmp/command-%d"%os.getpid()
92 if self.options.dry_run:
93 print 'dry_run',self.command
95 if self.options.verbose and self.options.mode not in Main.silent_modes:
96 print '+',self.command
98 return os.system(self.command)
100 def run_silent (self):
101 if self.options.dry_run:
102 print 'dry_run',self.command
104 if self.options.verbose:
105 print '+',self.command,' .. ',
107 retcod=os.system(self.command + " &> " + self.tmp)
109 print "FAILED ! -- out+err below (command was %s)"%self.command
110 os.system("cat " + self.tmp)
111 print "FAILED ! -- end of quoted output"
112 elif self.options.verbose:
118 if self.run_silent() !=0:
119 raise Exception,"Command %s failed"%self.command
121 # returns stdout, like bash's $(mycommand)
122 def output_of (self,with_stderr=False):
123 if self.options.dry_run:
124 print 'dry_run',self.command
125 return 'dry_run output'
126 tmp="/tmp/status-%d"%os.getpid()
127 if self.options.debug:
128 print '+',self.command,' .. ',
137 result=file(tmp).read()
139 if self.options.debug:
147 def __init__(self, path, options):
149 self.options = options
152 return os.path.basename(self.path)
155 out = Command("svn info %s" % self.path, self.options).output_of()
156 for line in out.split('\n'):
157 if line.startswith("URL:"):
158 return line.split()[1].strip()
161 out = Command("svn info %s" % self.path, self.options).output_of()
162 for line in out.split('\n'):
163 if line.startswith("Repository Root:"):
164 root = line.split()[2].strip()
165 return "%s/%s" % (root, self.name())
168 def checkout(cls, remote, local, options, recursive=False):
170 svncommand = "svn co %s %s" % (remote, local)
172 svncommand = "svn co -N %s %s" % (remote, local)
173 Command("rm -rf %s" % local, options).run_silent()
174 Command(svncommand, options).run_fatal()
176 return SvnRepository(local, options)
179 def remote_exists(cls, remote):
180 return os.system("svn list %s &> /dev/null" % remote) == 0
182 def tag_exists(self, tagname):
183 url = "%s/tags/%s" % (self.repo_root(), tagname)
184 return SvnRepository.remote_exists(url)
186 def update(self, subdir="", recursive=True):
187 path = os.path.join(self.path, subdir)
189 svncommand = "svn up %s" % path
191 svncommand = "svn up -N %s" % path
192 Command(svncommand, self.options).run_fatal()
194 def commit(self, logfile):
195 # add all new files to the repository
196 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
197 self.path, self.options).output_of()
198 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
200 def to_branch(self, branch):
201 remote = "%s/branches/%s" % (self.repo_root(), branch)
202 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
204 def to_tag(self, tag):
205 remote = "%s/tags/%s" % (self.repo_root(), branch)
206 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
208 def tag(self, tagname, logfile):
209 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
210 self_url = self.url()
211 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
213 def diff(self, f=""):
215 f = os.path.join(self.path, f)
218 return Command("svn diff %s" % f, self.options).output_of(True)
220 def diff_with_tag(self, tagname):
221 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
222 return Command("svn diff %s %s" % (tag_url, self.url()),
223 self.options).output_of(True)
225 def revert(self, f=""):
227 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
230 Command("svn revert %s -R" % self.path, self.options).run_fatal()
231 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
232 self.path, self.options).run_silent()
235 command="svn status %s" % self.path
236 return len(Command(command,self.options).output_of(True)) == 0
239 return os.path.exists(os.path.join(self.path, ".svn"))
245 def __init__(self, path, options):
247 self.options = options
250 return os.path.basename(self.path)
256 c = Command("git remote show origin", self.options)
257 out = self.__run_in_repo(c.output_of)
258 for line in out.split('\n'):
259 if line.strip().startswith("Fetch URL:"):
260 repo = line.split()[2]
263 def checkout(cls, remote, local, options, depth=1):
264 Command("rm -rf %s" % local, options).run_silent()
265 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
266 return GitRepository(local, options)
269 def remote_exists(cls, remote):
270 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
272 def tag_exists(self, tagname):
273 command = 'git tag -l | grep "^%s$"' % tagname
274 c = Command(command, self.options)
275 out = self.__run_in_repo(c.output_of, with_stderr=True)
278 def __run_in_repo(self, fun, *args, **kwargs):
281 ret = fun(*args, **kwargs)
285 def __run_command_in_repo(self, command, ignore_errors=False):
286 c = Command(command, self.options)
288 return self.__run_in_repo(c.output_of)
290 return self.__run_in_repo(c.run_fatal)
292 def update(self, subdir=None, recursive=None):
293 self.__run_command_in_repo("git fetch --tags")
294 self.__run_command_in_repo("git pull")
296 def to_branch(self, branch, remote=True):
298 branch = "origin/%s" % branch
299 return self.__run_command_in_repo("git checkout %s" % branch)
301 def to_tag(self, tag):
302 return self.__run_command_in_repo("git checkout %s" % tag)
304 def tag(self, tagname, logfile):
305 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
308 def diff(self, f=""):
309 c = Command("git diff %s" % f, self.options)
310 return self.__run_in_repo(c.output_of, with_stderr=True)
312 def diff_with_tag(self, tagname):
313 c = Command("git diff %s" % tagname, self.options)
314 return self.__run_in_repo(c.output_of, with_stderr=True)
316 def commit(self, logfile):
317 self.__run_command_in_repo("git add .", ignore_errors=True)
318 self.__run_command_in_repo("git add -u", ignore_errors=True)
319 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
320 self.__run_command_in_repo("git push")
321 self.__run_command_in_repo("git push --tags")
323 def revert(self, f=""):
325 self.__run_command_in_repo("git checkout %s" % f)
328 self.__run_command_in_repo("git --no-pager reset --hard")
329 self.__run_command_in_repo("git --no-pager clean -f")
334 s="nothing to commit (working directory clean)"
335 return Command(command, self.options).output_of(True).find(s) >= 0
336 return self.__run_in_repo(check_commit)
339 return os.path.exists(os.path.join(self.path, ".git"))
343 """ Generic repository """
344 supported_repo_types = [SvnRepository, GitRepository]
346 def __init__(self, path, options):
348 self.options = options
349 for repo in self.supported_repo_types:
350 self.repo = repo(self.path, self.options)
351 if self.repo.is_valid():
355 def has_moved_to_git(cls, module, svnpath):
356 module = git_to_svn_name(module)
357 return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (svnpath, module))
360 def remote_exists(cls, remote):
361 for repo in Repository.supported_repo_types:
362 if repo.remote_exists(remote):
366 def __getattr__(self, attr):
367 return getattr(self.repo, attr)
371 # support for tagged module is minimal, and is for the Build class only
374 svn_magic_line="--This line, and those below, will be ignored--"
375 setting_tag_format = "Setting tag %s"
377 redirectors=[ # ('module_name_varname','name'),
378 ('module_version_varname','version'),
379 ('module_taglevel_varname','taglevel'), ]
381 # where to store user's config
382 config_storage="CONFIG"
387 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
388 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
389 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
390 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
391 ("build", "Enter the name of your build module","build"),
392 ('username',"Enter your firstname and lastname for changelogs",""),
393 ("email","Enter your email address for changelogs",""),
397 def prompt_config_option(cls, key, message, default):
398 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
401 def prompt_config (cls):
402 for (key,message,default) in cls.configKeys:
404 while not cls.config[key]:
405 cls.prompt_config_option(key, message, default)
408 # for parsing module spec name:branch
409 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
410 # special form for tagged module - for Build
411 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
413 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
415 def __init__ (self,module_spec,options):
417 attempt=Module.matcher_branch_spec.match(module_spec)
419 self.name=attempt.group('name')
420 self.branch=attempt.group('branch')
422 attempt=Module.matcher_tag_spec.match(module_spec)
424 self.name=attempt.group('name')
425 self.tagname=attempt.group('tagname')
427 self.name=module_spec
429 # when available prefer to use git module name internally
430 self.name = svn_to_git_name(self.name)
433 self.module_dir="%s/%s"%(options.workdir,self.name)
434 self.repository = None
437 def run (self,command):
438 return Command(command,self.options).run()
439 def run_fatal (self,command):
440 return Command(command,self.options).run_fatal()
441 def run_prompt (self,message,fun, *args):
442 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
443 if not self.options.verbose:
445 choice=prompt(message,True,('s','how'))
449 elif choice is False:
450 print 'About to run function:', fun_msg
452 question=message+" - want to run function: " + fun_msg
453 if prompt(question,True):
456 def friendly_name (self):
457 if hasattr(self,'branch'):
458 return "%s:%s"%(self.name,self.branch)
459 elif hasattr(self,'tagname'):
460 return "%s@%s"%(self.name,self.tagname)
465 def git_remote_dir (cls, name):
466 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
469 def svn_remote_dir (cls, name):
470 name = git_to_svn_name(name)
471 svn = cls.config['svnpath']
472 if svn.endswith('/'):
473 return "%s%s" % (svn, name)
474 return "%s/%s" % (svn, name)
476 def svn_selected_remote(self):
477 svn_name = git_to_svn_name(self.name)
478 remote = self.svn_remote_dir(svn_name)
479 if hasattr(self,'branch'):
480 remote = "%s/branches/%s" % (remote, self.branch)
481 elif hasattr(self,'tagname'):
482 remote = "%s/tags/%s" % (remote, self.tagname)
484 remote = "%s/trunk" % remote
489 def init_homedir (cls, options):
490 if options.verbose and options.mode not in Main.silent_modes:
491 print 'Checking for', options.workdir
492 storage="%s/%s"%(options.workdir, cls.config_storage)
493 # sanity check. Either the topdir exists AND we have a config/storage
494 # or topdir does not exist and we create it
495 # to avoid people use their own daily svn repo
496 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
497 print """The directory %s exists and has no CONFIG file
498 If this is your regular working directory, please provide another one as the
499 module-* commands need a fresh working dir. Make sure that you do not use
500 that for other purposes than tagging""" % options.workdir
503 def checkout_build():
504 print "Checking out build module..."
505 remote = cls.git_remote_dir(cls.config['build'])
506 local = os.path.join(options.workdir, cls.config['build'])
507 GitRepository.checkout(remote, local, options, depth=1)
512 for (key,message,default) in Module.configKeys:
513 f.write("%s=%s\n"%(key,Module.config[key]))
516 print 'Stored',storage
517 Command("cat %s"%storage,options).run()
522 for line in f.readlines():
523 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
524 Module.config[key]=value
527 if not os.path.isdir (options.workdir):
528 print "Cannot find",options.workdir,"let's create it"
529 Command("mkdir -p %s" % options.workdir, options).run_silent()
535 # check missing config options
537 for (key,message,default) in cls.configKeys:
538 if not Module.config.has_key(key):
539 print "Configuration changed for module-tools"
540 cls.prompt_config_option(key, message, default)
544 Command("rm -rf %s" % options.workdir, options).run_silent()
545 Command("mkdir -p %s" % options.workdir, options).run_silent()
549 build_dir = os.path.join(options.workdir, cls.config['build'])
550 if not os.path.isdir(build_dir):
553 build = Repository(build_dir, options)
554 if not build.is_clean():
555 print "build module needs a revert"
560 if options.verbose and options.mode not in Main.silent_modes:
561 print '******** Using config'
562 for (key,message,default) in Module.configKeys:
563 print '\t',key,'=',Module.config[key]
565 def init_module_dir (self):
566 if self.options.verbose:
567 print 'Checking for',self.module_dir
569 if not os.path.isdir (self.module_dir):
570 if Repository.has_moved_to_git(self.name, Module.config['svnpath']):
571 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
575 remote = self.svn_selected_remote()
576 self.repository = SvnRepository.checkout(remote,
578 self.options, recursive=False)
580 self.repository = Repository(self.module_dir, self.options)
581 if self.repository.type == "svn":
582 # check if module has moved to git
583 if Repository.has_moved_to_git(self.name, Module.config['svnpath']):
584 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
585 self.init_module_dir()
586 # check if we have the required branch/tag
587 if self.repository.url() != self.svn_selected_remote():
588 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
589 self.init_module_dir()
591 elif self.repository.type == "git":
592 if hasattr(self,'branch'):
593 self.repository.to_branch(self.branch)
594 elif hasattr(self,'tagname'):
595 self.repository.to_tag(self.tagname)
598 raise Exception, 'Cannot find %s - check module name'%self.module_dir
601 def revert_module_dir (self):
602 if self.options.fast_checks:
603 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
605 if self.options.verbose:
606 print 'Checking whether', self.module_dir, 'needs being reverted'
608 if not self.repository.is_clean():
609 self.repository.revert()
611 def update_module_dir (self):
612 if self.options.fast_checks:
613 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
615 if self.options.verbose:
616 print 'Updating', self.module_dir
617 self.repository.update()
619 def main_specname (self):
620 attempt="%s/%s.spec"%(self.module_dir,self.name)
621 if os.path.isfile (attempt):
623 pattern1="%s/*.spec"%self.module_dir
624 level1=glob(pattern1)
627 pattern2="%s/*/*.spec"%self.module_dir
628 level2=glob(pattern2)
632 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
634 def all_specnames (self):
635 level1=glob("%s/*.spec" % self.module_dir)
636 if level1: return level1
637 level2=glob("%s/*/*.spec" % self.module_dir)
640 def parse_spec (self, specfile, varnames):
641 if self.options.verbose:
642 print 'Parsing',specfile,
648 for line in f.readlines():
649 attempt=Module.matcher_rpm_define.match(line)
651 (define,var,value)=attempt.groups()
655 if self.options.debug:
656 print 'found',len(result),'keys'
657 for (k,v) in result.iteritems():
661 # stores in self.module_name_varname the rpm variable to be used for the module's name
662 # and the list of these names in self.varnames
663 def spec_dict (self):
664 specfile=self.main_specname()
665 redirector_keys = [ varname for (varname,default) in Module.redirectors]
666 redirect_dict = self.parse_spec(specfile,redirector_keys)
667 if self.options.debug:
668 print '1st pass parsing done, redirect_dict=',redirect_dict
670 for (varname,default) in Module.redirectors:
671 if redirect_dict.has_key(varname):
672 setattr(self,varname,redirect_dict[varname])
673 varnames += [redirect_dict[varname]]
675 setattr(self,varname,default)
676 varnames += [ default ]
677 self.varnames = varnames
678 result = self.parse_spec (specfile,self.varnames)
679 if self.options.debug:
680 print '2st pass parsing done, varnames=',varnames,'result=',result
683 def patch_spec_var (self, patch_dict,define_missing=False):
684 for specfile in self.all_specnames():
685 # record the keys that were changed
686 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
687 newspecfile=specfile+".new"
688 if self.options.verbose:
689 print 'Patching',specfile,'for',patch_dict.keys()
691 new=open(newspecfile,"w")
693 for line in spec.readlines():
694 attempt=Module.matcher_rpm_define.match(line)
696 (define,var,value)=attempt.groups()
697 if var in patch_dict.keys():
698 if self.options.debug:
699 print 'rewriting %s as %s'%(var,patch_dict[var])
700 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
705 for (key,was_changed) in changed.iteritems():
707 if self.options.debug:
708 print 'rewriting missing %s as %s'%(key,patch_dict[key])
709 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
712 os.rename(newspecfile,specfile)
714 # returns all lines until the magic line
715 def unignored_lines (self, logfile):
717 white_line_matcher = re.compile("\A\s*\Z")
718 for logline in file(logfile).readlines():
719 if logline.strip() == Module.svn_magic_line:
721 elif white_line_matcher.match(logline):
724 result.append(logline.strip()+'\n')
727 # creates a copy of the input with only the unignored lines
728 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
730 f.write(self.setting_tag_format%new_tag_name + '\n')
731 for line in self.unignored_lines(filein):
735 def insert_changelog (self, logfile, oldtag, newtag):
736 for specfile in self.all_specnames():
737 newspecfile=specfile+".new"
738 if self.options.verbose:
739 print 'Inserting changelog from %s into %s'%(logfile,specfile)
741 new=open(newspecfile,"w")
742 for line in spec.readlines():
744 if re.compile('%changelog').match(line):
745 dateformat="* %a %b %d %Y"
746 datepart=time.strftime(dateformat)
747 logpart="%s <%s> - %s"%(Module.config['username'],
748 Module.config['email'],
750 new.write(datepart+" "+logpart+"\n")
751 for logline in self.unignored_lines(logfile):
752 new.write("- " + logline)
756 os.rename(newspecfile,specfile)
758 def show_dict (self, spec_dict):
759 if self.options.verbose:
760 for (k,v) in spec_dict.iteritems():
763 def last_tag (self, spec_dict):
765 return "%s-%s" % (spec_dict[self.module_version_varname],
766 spec_dict[self.module_taglevel_varname])
768 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
770 def tag_name (self, spec_dict, old_svn_name=False):
771 base_tag_name = self.name
773 base_tag_name = git_to_svn_name(self.name)
774 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
777 ##############################
778 # using fine_grain means replacing only those instances that currently refer to this tag
779 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
780 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
781 newtagsfile=tagsfile+".new"
783 new=open(newtagsfile,"w")
786 # fine-grain : replace those lines that refer to oldname
788 if self.options.verbose:
789 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
790 matcher=re.compile("^(.*)%s(.*)"%oldname)
791 for line in tags.readlines():
792 if not matcher.match(line):
795 (begin,end)=matcher.match(line).groups()
796 new.write(begin+newname+end+"\n")
798 # brute-force : change uncommented lines that define <module>-SVNPATH
800 if self.options.verbose:
801 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
802 pattern="\A\s*(?P<make_name>[^\s]+)-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
804 matcher_module=re.compile(pattern)
805 for line in tags.readlines():
806 attempt=matcher_module.match(line)
808 if line.find("-GITPATH") >= 0:
809 modulepath = "%s-GITPATH"%(attempt.group('make_name'))
810 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
812 moduleath="%s-SVNPATH"%(attempt.group('make_name'))
813 replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
814 if self.options.verbose:
815 print ' ' + modulepath,
816 new.write(replacement)
822 os.rename(newtagsfile,tagsfile)
823 if self.options.verbose: print "%d changes"%matches
826 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
827 if self.options.verbose:
828 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
830 found_tagname = tagname
831 found = self.repository.tag_exists(tagname)
832 if not found and old_svn_tag_name:
833 if self.options.verbose:
835 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
836 found = self.repository.tag_exists(old_svn_tag_name)
838 found_tagname = old_svn_tag_name
840 if (found and need_it) or (not found and not need_it):
841 if self.options.verbose:
843 if found: print "- found"
844 else: print "- not found"
846 if self.options.verbose:
849 raise Exception, "tag (%s) is already there" % tagname
851 raise Exception, "can not find required tag (%s)" % tagname
856 ##############################
858 self.init_module_dir()
859 self.revert_module_dir()
860 self.update_module_dir()
862 spec_dict = self.spec_dict()
863 self.show_dict(spec_dict)
866 old_tag_name = self.tag_name(spec_dict)
867 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
869 if (self.options.new_version):
870 # new version set on command line
871 spec_dict[self.module_version_varname] = self.options.new_version
872 spec_dict[self.module_taglevel_varname] = 0
875 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
876 spec_dict[self.module_taglevel_varname] = new_taglevel
878 new_tag_name = self.tag_name(spec_dict)
881 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
882 new_tag_name = self.check_tag(new_tag_name, need_it=False)
885 diff_output = self.repository.diff_with_tag(old_tag_name)
886 if len(diff_output) == 0:
887 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
890 # side effect in trunk's specfile
891 self.patch_spec_var(spec_dict)
893 # prepare changelog file
894 # we use the standard subversion magic string (see svn_magic_line)
895 # so we can provide useful information, such as version numbers and diff
897 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
898 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
899 setting_tag_line=Module.setting_tag_format%new_tag_name
900 file(changelog,"w").write("""
903 Please write a changelog for this new tag in the section above
904 """%(Module.svn_magic_line,setting_tag_line))
906 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
907 file(changelog,"a").write('DIFF=========\n' + diff_output)
909 if self.options.debug:
913 self.run("%s %s"%(self.options.editor,changelog))
914 # strip magic line in second file - looks like svn has changed its magic line with 1.6
915 # so we do the job ourselves
916 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
917 # insert changelog in spec
918 if self.options.changelog:
919 self.insert_changelog (changelog,old_tag_name,new_tag_name)
922 build_path = os.path.join(self.options.workdir,
923 Module.config['build'])
924 build = Repository(build_path, self.options)
925 if self.options.build_branch:
926 build.to_branch(self.options.build_branch)
927 if not build.is_clean():
930 tagsfiles=glob(build.path+"/*-tags*.mk")
931 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
935 for tagsfile in tagsfiles:
936 status=tagsdict[tagsfile]
937 basename=os.path.basename(tagsfile)
938 print ".................... Dealing with %s"%basename
939 while tagsdict[tagsfile] == 'todo' :
940 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
941 [ ('y','es'), ('n', 'ext'), ('f','orce'),
942 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
945 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
947 print 'Done with %s'%os.path.basename(tagsfile)
948 tagsdict[tagsfile]='done'
950 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
952 print build.diff(f=tagsfile)
954 build.revert(f=tagsfile)
956 self.run("cat %s"%tagsfile)
959 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
960 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
961 d: show current diff for this tag file
962 r: revert that tag file
963 c: cat the current tag file
964 n: move to next file"""%locals()
966 if prompt("Want to review changes on tags files",False):
967 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
972 def diff_all_changes():
974 print self.repository.diff()
976 def commit_all_changes(log):
977 self.repository.commit(log)
980 self.run_prompt("Review module and build", diff_all_changes)
981 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
982 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
984 if self.options.debug:
985 print 'Preserving',changelog,'and stripped',changelog_svn
988 os.unlink(changelog_svn)
991 ##############################
992 def do_version (self):
993 self.init_module_dir()
994 self.revert_module_dir()
995 self.update_module_dir()
996 spec_dict = self.spec_dict()
998 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
999 self.last_tag(spec_dict)))
1000 for varname in self.varnames:
1001 if not spec_dict.has_key(varname):
1002 self.html_print ('Could not find %%define for %s'%varname)
1005 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1006 if self.options.verbose:
1007 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1008 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1009 self.html_print_end()
1012 ##############################
1014 self.init_module_dir()
1015 self.revert_module_dir()
1016 self.update_module_dir()
1017 spec_dict = self.spec_dict()
1018 self.show_dict(spec_dict)
1021 tag_name = self.tag_name(spec_dict)
1022 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1025 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1027 if self.options.verbose:
1028 print 'Getting diff'
1029 diff_output = self.repository.diff_with_tag(tag_name)
1031 if self.options.list:
1035 thename=self.friendly_name()
1037 if self.options.www and diff_output:
1038 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1039 thename,self.last_tag(spec_dict),len(diff_output)))
1041 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1042 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1043 self.html_store_pre (diff_output)
1044 elif not self.options.www:
1045 print 'x'*30,'module',thename
1046 print 'x'*20,'<',tag_name
1047 print 'x'*20,'>',thename
1050 ##############################
1051 # store and restitute html fragments
1053 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1056 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1059 def html_quote (text):
1060 return text.replace('&','&').replace('<','<').replace('>','>')
1062 # only the fake error module has multiple titles
1063 def html_store_title (self, title):
1064 if not hasattr(self,'titles'): self.titles=[]
1065 self.titles.append(title)
1067 def html_store_raw (self, html):
1068 if not hasattr(self,'body'): self.body=''
1071 def html_store_pre (self, text):
1072 if not hasattr(self,'body'): self.body=''
1073 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1075 def html_print (self, txt):
1076 if not self.options.www:
1079 if not hasattr(self,'in_list') or not self.in_list:
1080 self.html_store_raw('<ul>')
1082 self.html_store_raw('<li>'+txt+'</li>')
1084 def html_print_end (self):
1085 if self.options.www:
1086 self.html_store_raw ('</ul>')
1089 def html_dump_header(title):
1090 nowdate=time.strftime("%Y-%m-%d")
1091 nowtime=time.strftime("%H:%M (%Z)")
1092 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1093 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1096 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1097 <style type="text/css">
1098 body { font-family:georgia, serif; }
1099 h1 {font-size: large; }
1100 p.title {font-size: x-large; }
1101 span.error {text-weight:bold; color: red; }
1105 <p class='title'> %s - status on %s at %s</p>
1107 """%(title,title,nowdate,nowtime)
1110 def html_dump_middle():
1114 def html_dump_footer():
1115 print "</body></html"
1117 def html_dump_toc(self):
1118 if hasattr(self,'titles'):
1119 for title in self.titles:
1120 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1122 def html_dump_body(self):
1123 if hasattr(self,'titles'):
1124 for title in self.titles:
1125 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1126 if hasattr(self,'body'):
1128 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1131 ##############################
1134 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1136 module-tools : a set of tools to manage subversion tags and specfile
1137 requires the specfile to either
1138 * define *version* and *taglevel*
1140 * define redirection variables module_version_varname / module_taglevel_varname
1142 by default, the trunk of modules is taken into account
1143 in this case, just mention the module name as <module_desc>
1145 if you wish to work on a branch rather than on the trunk,
1146 you can use something like e.g. Mom:2.1 as <module_desc>
1148 release_usage="""Usage: %prog [options] tag1 .. tagn
1149 Extract release notes from the changes in specfiles between several build tags, latest first
1151 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1152 You can refer to a (build) branch by prepending a colon, like in
1153 release-changelog :4.2 4.2-rc25
1154 You can refer to the build trunk by just mentioning 'trunk', e.g.
1155 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1157 common_usage="""More help:
1158 see http://svn.planet-lab.org/wiki/ModuleTools"""
1161 'list' : "displays a list of available tags or branches",
1162 'version' : "check latest specfile and print out details",
1163 'diff' : "show difference between module (trunk or branch) and latest tag",
1164 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1165 create new tag and and monitor its adoption in build/*-tags*.mk""",
1166 'branch' : """create a branch for this module, from the latest tag on the trunk,
1167 and change trunk's version number to reflect the new branch name;
1168 you can specify the new branch name by using module:branch""",
1169 'sync' : """create a tag from the module
1170 this is a last resort option, mostly for repairs""",
1171 'changelog' : """extract changelog between build tags
1172 expected arguments are a list of tags""",
1175 silent_modes = ['list']
1176 release_modes = ['changelog']
1179 def optparse_list (option, opt, value, parser):
1181 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1183 setattr(parser.values,option.dest,value.split())
1188 for function in Main.modes.keys():
1189 if sys.argv[0].find(function) >= 0:
1193 print "Unsupported command",sys.argv[0]
1194 print "Supported commands:" + " ".join(Main.modes.keys())
1197 if mode not in Main.release_modes:
1198 usage = Main.module_usage
1199 usage += Main.common_usage
1200 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1202 usage = Main.release_usage
1203 usage += Main.common_usage
1205 parser=OptionParser(usage=usage)
1207 if mode == "tag" or mode == 'branch':
1208 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1209 help="set new version and reset taglevel to 0")
1211 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1212 help="do not update changelog section in specfile when tagging")
1213 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1214 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1215 if mode == "tag" or mode == "sync" :
1216 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1217 help="specify editor")
1219 if mode in ["diff","version"] :
1220 parser.add_option("-W","--www", action="store", dest="www", default=False,
1221 help="export diff in html format, e.g. -W trunk")
1224 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1225 help="just list modules that exhibit differences")
1227 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1228 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1229 help="run on all modules as found in %s"%default_modules_list)
1230 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1231 help="run on all modules found in specified file")
1232 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1233 help="dry run - shell commands are only displayed")
1234 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1235 default=[], nargs=1,type="string",
1236 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1237 -- can be set multiple times, or use quotes""")
1239 parser.add_option("-w","--workdir", action="store", dest="workdir",
1240 default="%s/%s"%(os.getenv("HOME"),"modules"),
1241 help="""name for dedicated working dir - defaults to ~/modules
1242 ** THIS MUST NOT ** be your usual working directory""")
1243 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1244 help="skip safety checks, such as svn updates -- use with care")
1246 # default verbosity depending on function - temp
1247 verbose_modes= ['tag', 'sync', 'branch']
1249 if mode not in verbose_modes:
1250 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1251 help="run in verbose mode")
1253 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1254 help="run in quiet (non-verbose) mode")
1255 (options, args) = parser.parse_args()
1257 if not hasattr(options,'dry_run'):
1258 options.dry_run=False
1259 if not hasattr(options,'www'):
1265 if options.all_modules:
1266 options.modules_list=default_modules_list
1267 if options.modules_list:
1268 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1272 Module.init_homedir(options)
1275 modules=[ Module(modname,options) for modname in args ]
1276 # hack: create a dummy Module to store errors/warnings
1277 error_module = Module('__errors__',options)
1279 for module in modules:
1280 if len(args)>1 and mode not in Main.silent_modes:
1282 print '========================================',module.friendly_name()
1283 # call the method called do_<mode>
1284 method=Module.__dict__["do_%s"%mode]
1289 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1290 (module.friendly_name(), str(e))
1291 error_module.html_store_title(title)
1294 traceback.print_exc()
1295 print 'Skipping module %s: '%modname,e
1299 modetitle="Changes to tag in %s"%options.www
1300 elif mode == "version":
1301 modetitle="Latest tags in %s"%options.www
1302 modules.append(error_module)
1303 error_module.html_dump_header(modetitle)
1304 for module in modules:
1305 module.html_dump_toc()
1306 Module.html_dump_middle()
1307 for module in modules:
1308 module.html_dump_body()
1309 Module.html_dump_footer()
1311 ####################
1312 if __name__ == "__main__" :
1315 except KeyboardInterrupt: