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 = {
16 "BootManager": "bootmanager",
18 "VserverReference": "vserverreference",
19 "BootstrapFS": "bootstrapfs",
23 def svn_to_git_name(module):
24 if RENAMED_SVN_MODULES.has_key(module):
25 return RENAMED_SVN_MODULES[module]
28 def git_to_svn_name(module):
29 for key in RENAMED_SVN_MODULES:
30 if module == RENAMED_SVN_MODULES[key]:
35 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
36 def prompt (question,default=True,other_choices=[],allow_outside=False):
37 if not isinstance (other_choices,list):
38 other_choices = [ other_choices ]
39 chars = [ c for (c,rest) in other_choices ]
43 if default is True: choices.append('[y]')
44 else : choices.append('y')
46 if default is False: choices.append('[n]')
47 else : choices.append('n')
49 for (char,choice) in other_choices:
51 choices.append("["+char+"]"+choice)
53 choices.append("<"+char+">"+choice)
55 answer=raw_input(question + " " + "/".join(choices) + " ? ")
58 answer=answer[0].lower()
60 if 'y' in chars: return 'y'
63 if 'n' in chars: return 'n'
66 for (char,choice) in other_choices:
71 return prompt(question,default,other_choices)
77 editor = os.environ['EDITOR']
85 def print_fold (line):
86 while len(line) >= fold_length:
87 print line[:fold_length],'\\'
88 line=line[fold_length:]
92 def __init__ (self,command,options):
95 self.tmp="/tmp/command-%d"%os.getpid()
98 if self.options.dry_run:
99 print 'dry_run',self.command
101 if self.options.verbose and self.options.mode not in Main.silent_modes:
102 print '+',self.command
104 return os.system(self.command)
106 def run_silent (self):
107 if self.options.dry_run:
108 print 'dry_run',self.command
110 if self.options.verbose:
111 print '+',self.command,' .. ',
113 retcod=os.system(self.command + " &> " + self.tmp)
115 print "FAILED ! -- out+err below (command was %s)"%self.command
116 os.system("cat " + self.tmp)
117 print "FAILED ! -- end of quoted output"
118 elif self.options.verbose:
124 if self.run_silent() !=0:
125 raise Exception,"Command %s failed"%self.command
127 # returns stdout, like bash's $(mycommand)
128 def output_of (self,with_stderr=False):
129 if self.options.dry_run:
130 print 'dry_run',self.command
131 return 'dry_run output'
132 tmp="/tmp/status-%d"%os.getpid()
133 if self.options.debug:
134 print '+',self.command,' .. ',
143 result=file(tmp).read()
145 if self.options.debug:
153 def __init__(self, path, options):
155 self.options = options
158 return os.path.basename(self.path)
161 out = Command("svn info %s" % self.path, self.options).output_of()
162 for line in out.split('\n'):
163 if line.startswith("URL:"):
164 return line.split()[1].strip()
167 out = Command("svn info %s" % self.path, self.options).output_of()
168 for line in out.split('\n'):
169 if line.startswith("Repository Root:"):
170 root = line.split()[2].strip()
171 return "%s/%s" % (root, self.name())
174 def checkout(cls, remote, local, options, recursive=False):
176 svncommand = "svn co %s %s" % (remote, local)
178 svncommand = "svn co -N %s %s" % (remote, local)
179 Command("rm -rf %s" % local, options).run_silent()
180 Command(svncommand, options).run_fatal()
182 return SvnRepository(local, options)
185 def remote_exists(cls, remote):
186 return os.system("svn list %s &> /dev/null" % remote) == 0
188 def tag_exists(self, tagname):
189 url = "%s/tags/%s" % (self.repo_root(), tagname)
190 return SvnRepository.remote_exists(url)
192 def update(self, subdir="", recursive=True, branch=None):
193 path = os.path.join(self.path, subdir)
195 svncommand = "svn up %s" % path
197 svncommand = "svn up -N %s" % path
198 Command(svncommand, self.options).run_fatal()
200 def commit(self, logfile):
201 # add all new files to the repository
202 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
203 self.path, self.options).output_of()
204 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
206 def to_branch(self, branch):
207 remote = "%s/branches/%s" % (self.repo_root(), branch)
208 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
210 def to_tag(self, tag):
211 remote = "%s/tags/%s" % (self.repo_root(), branch)
212 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
214 def tag(self, tagname, logfile):
215 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
216 self_url = self.url()
217 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
219 def diff(self, f=""):
221 f = os.path.join(self.path, f)
224 return Command("svn diff %s" % f, self.options).output_of(True)
226 def diff_with_tag(self, tagname):
227 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
228 return Command("svn diff %s %s" % (tag_url, self.url()),
229 self.options).output_of(True)
231 def revert(self, f=""):
233 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
236 Command("svn revert %s -R" % self.path, self.options).run_fatal()
237 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
238 self.path, self.options).run_silent()
241 command="svn status %s" % self.path
242 return len(Command(command,self.options).output_of(True)) == 0
245 return os.path.exists(os.path.join(self.path, ".svn"))
251 def __init__(self, path, options):
253 self.options = options
256 return os.path.basename(self.path)
262 c = Command("git remote show origin", self.options)
263 out = self.__run_in_repo(c.output_of)
264 for line in out.split('\n'):
265 if line.strip().startswith("Fetch URL:"):
266 repo = line.split()[2]
269 def checkout(cls, remote, local, options, depth=1):
270 Command("rm -rf %s" % local, options).run_silent()
271 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
272 return GitRepository(local, options)
275 def remote_exists(cls, remote):
276 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
278 def tag_exists(self, tagname):
279 command = 'git tag -l | grep "^%s$"' % tagname
280 c = Command(command, self.options)
281 out = self.__run_in_repo(c.output_of, with_stderr=True)
284 def __run_in_repo(self, fun, *args, **kwargs):
287 ret = fun(*args, **kwargs)
291 def __run_command_in_repo(self, command, ignore_errors=False):
292 c = Command(command, self.options)
294 return self.__run_in_repo(c.output_of)
296 return self.__run_in_repo(c.run_fatal)
298 def update(self, subdir=None, recursive=None, branch="master"):
299 if branch == "master":
300 self.__run_command_in_repo("git checkout %s" % branch)
302 self.__run_command_in_repo("git checkout origin/%s" % branch)
303 self.__run_command_in_repo("git fetch origin --tags")
304 self.__run_command_in_repo("git fetch origin")
305 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
307 def to_branch(self, branch, remote=True):
309 branch = "origin/%s" % branch
310 return self.__run_command_in_repo("git checkout %s" % branch)
312 def to_tag(self, tag):
313 return self.__run_command_in_repo("git checkout %s" % tag)
315 def tag(self, tagname, logfile):
316 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
319 def diff(self, f=""):
320 c = Command("git diff %s" % f, self.options)
321 return self.__run_in_repo(c.output_of, with_stderr=True)
323 def diff_with_tag(self, tagname):
324 c = Command("git diff %s" % tagname, self.options)
325 return self.__run_in_repo(c.output_of, with_stderr=True)
327 def commit(self, logfile):
328 self.__run_command_in_repo("git add .", ignore_errors=True)
329 self.__run_command_in_repo("git add -u", ignore_errors=True)
330 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
331 self.__run_command_in_repo("git push")
332 self.__run_command_in_repo("git push --tags")
334 def revert(self, f=""):
336 self.__run_command_in_repo("git checkout %s" % f)
339 self.__run_command_in_repo("git --no-pager reset --hard")
340 self.__run_command_in_repo("git --no-pager clean -f")
345 s="nothing to commit (working directory clean)"
346 return Command(command, self.options).output_of(True).find(s) >= 0
347 return self.__run_in_repo(check_commit)
350 return os.path.exists(os.path.join(self.path, ".git"))
354 """ Generic repository """
355 supported_repo_types = [SvnRepository, GitRepository]
357 def __init__(self, path, options):
359 self.options = options
360 for repo in self.supported_repo_types:
361 self.repo = repo(self.path, self.options)
362 if self.repo.is_valid():
366 def has_moved_to_git(cls, module, config):
367 module = git_to_svn_name(module)
368 # check if the module is already in Git
369 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
370 return GitRepository.remote_exists(Module.git_remote_dir(module))
374 def remote_exists(cls, remote):
375 for repo in Repository.supported_repo_types:
376 if repo.remote_exists(remote):
380 def __getattr__(self, attr):
381 return getattr(self.repo, attr)
385 # support for tagged module is minimal, and is for the Build class only
388 svn_magic_line="--This line, and those below, will be ignored--"
389 setting_tag_format = "Setting tag %s"
391 redirectors=[ # ('module_name_varname','name'),
392 ('module_version_varname','version'),
393 ('module_taglevel_varname','taglevel'), ]
395 # where to store user's config
396 config_storage="CONFIG"
401 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
402 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
403 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
404 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
405 ("build", "Enter the name of your build module","build"),
406 ('username',"Enter your firstname and lastname for changelogs",""),
407 ("email","Enter your email address for changelogs",""),
411 def prompt_config_option(cls, key, message, default):
412 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
415 def prompt_config (cls):
416 for (key,message,default) in cls.configKeys:
418 while not cls.config[key]:
419 cls.prompt_config_option(key, message, default)
422 # for parsing module spec name:branch
423 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
424 # special form for tagged module - for Build
425 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
427 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
429 def __init__ (self,module_spec,options):
431 attempt=Module.matcher_branch_spec.match(module_spec)
433 self.name=attempt.group('name')
434 self.branch=attempt.group('branch')
436 attempt=Module.matcher_tag_spec.match(module_spec)
438 self.name=attempt.group('name')
439 self.tagname=attempt.group('tagname')
441 self.name=module_spec
443 # when available prefer to use git module name internally
444 self.name = svn_to_git_name(self.name)
447 self.module_dir="%s/%s"%(options.workdir,self.name)
448 self.repository = None
451 def run (self,command):
452 return Command(command,self.options).run()
453 def run_fatal (self,command):
454 return Command(command,self.options).run_fatal()
455 def run_prompt (self,message,fun, *args):
456 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
457 if not self.options.verbose:
459 choice=prompt(message,True,('s','how'))
463 elif choice is False:
464 print 'About to run function:', fun_msg
466 question=message+" - want to run function: " + fun_msg
467 if prompt(question,True):
470 def friendly_name (self):
471 if hasattr(self,'branch'):
472 return "%s:%s"%(self.name,self.branch)
473 elif hasattr(self,'tagname'):
474 return "%s@%s"%(self.name,self.tagname)
479 def git_remote_dir (cls, name):
480 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
483 def svn_remote_dir (cls, name):
484 name = git_to_svn_name(name)
485 svn = cls.config['svnpath']
486 if svn.endswith('/'):
487 return "%s%s" % (svn, name)
488 return "%s/%s" % (svn, name)
490 def svn_selected_remote(self):
491 svn_name = git_to_svn_name(self.name)
492 remote = self.svn_remote_dir(svn_name)
493 if hasattr(self,'branch'):
494 remote = "%s/branches/%s" % (remote, self.branch)
495 elif hasattr(self,'tagname'):
496 remote = "%s/tags/%s" % (remote, self.tagname)
498 remote = "%s/trunk" % remote
503 def init_homedir (cls, options):
504 if options.verbose and options.mode not in Main.silent_modes:
505 print 'Checking for', options.workdir
506 storage="%s/%s"%(options.workdir, cls.config_storage)
507 # sanity check. Either the topdir exists AND we have a config/storage
508 # or topdir does not exist and we create it
509 # to avoid people use their own daily svn repo
510 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
511 print """The directory %s exists and has no CONFIG file
512 If this is your regular working directory, please provide another one as the
513 module-* commands need a fresh working dir. Make sure that you do not use
514 that for other purposes than tagging""" % options.workdir
517 def checkout_build():
518 print "Checking out build module..."
519 remote = cls.git_remote_dir(cls.config['build'])
520 local = os.path.join(options.workdir, cls.config['build'])
521 GitRepository.checkout(remote, local, options, depth=1)
526 for (key,message,default) in Module.configKeys:
527 f.write("%s=%s\n"%(key,Module.config[key]))
530 print 'Stored',storage
531 Command("cat %s"%storage,options).run()
536 for line in f.readlines():
537 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
538 Module.config[key]=value
541 if not os.path.isdir (options.workdir):
542 print "Cannot find",options.workdir,"let's create it"
543 Command("mkdir -p %s" % options.workdir, options).run_silent()
549 # check missing config options
551 for (key,message,default) in cls.configKeys:
552 if not Module.config.has_key(key):
553 print "Configuration changed for module-tools"
554 cls.prompt_config_option(key, message, default)
558 Command("rm -rf %s" % options.workdir, options).run_silent()
559 Command("mkdir -p %s" % options.workdir, options).run_silent()
563 build_dir = os.path.join(options.workdir, cls.config['build'])
564 if not os.path.isdir(build_dir):
567 build = Repository(build_dir, options)
568 if not build.is_clean():
569 print "build module needs a revert"
574 if options.verbose and options.mode not in Main.silent_modes:
575 print '******** Using config'
576 for (key,message,default) in Module.configKeys:
577 print '\t',key,'=',Module.config[key]
579 def init_module_dir (self):
580 if self.options.verbose:
581 print 'Checking for',self.module_dir
583 if not os.path.isdir (self.module_dir):
584 if Repository.has_moved_to_git(self.name, Module.config):
585 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
589 remote = self.svn_selected_remote()
590 self.repository = SvnRepository.checkout(remote,
592 self.options, recursive=False)
594 self.repository = Repository(self.module_dir, self.options)
595 if self.repository.type == "svn":
596 # check if module has moved to git
597 if Repository.has_moved_to_git(self.name, Module.config):
598 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
599 self.init_module_dir()
600 # check if we have the required branch/tag
601 if self.repository.url() != self.svn_selected_remote():
602 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
603 self.init_module_dir()
605 elif self.repository.type == "git":
606 if hasattr(self,'branch'):
607 self.repository.to_branch(self.branch)
608 elif hasattr(self,'tagname'):
609 self.repository.to_tag(self.tagname)
612 raise Exception, 'Cannot find %s - check module name'%self.module_dir
615 def revert_module_dir (self):
616 if self.options.fast_checks:
617 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
619 if self.options.verbose:
620 print 'Checking whether', self.module_dir, 'needs being reverted'
622 if not self.repository.is_clean():
623 self.repository.revert()
625 def update_module_dir (self):
626 if self.options.fast_checks:
627 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
629 if self.options.verbose:
630 print 'Updating', self.module_dir
632 if hasattr(self,'branch'):
633 self.repository.update(branch=self.branch)
634 elif hasattr(self,'tagname'):
635 self.repository.update(branch=self.tagname)
637 self.repository.update()
639 def main_specname (self):
640 attempt="%s/%s.spec"%(self.module_dir,self.name)
641 if os.path.isfile (attempt):
643 pattern1="%s/*.spec"%self.module_dir
644 level1=glob(pattern1)
647 pattern2="%s/*/*.spec"%self.module_dir
648 level2=glob(pattern2)
652 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
654 def all_specnames (self):
655 level1=glob("%s/*.spec" % self.module_dir)
656 if level1: return level1
657 level2=glob("%s/*/*.spec" % self.module_dir)
660 def parse_spec (self, specfile, varnames):
661 if self.options.verbose:
662 print 'Parsing',specfile,
668 for line in f.readlines():
669 attempt=Module.matcher_rpm_define.match(line)
671 (define,var,value)=attempt.groups()
675 if self.options.debug:
676 print 'found',len(result),'keys'
677 for (k,v) in result.iteritems():
681 # stores in self.module_name_varname the rpm variable to be used for the module's name
682 # and the list of these names in self.varnames
683 def spec_dict (self):
684 specfile=self.main_specname()
685 redirector_keys = [ varname for (varname,default) in Module.redirectors]
686 redirect_dict = self.parse_spec(specfile,redirector_keys)
687 if self.options.debug:
688 print '1st pass parsing done, redirect_dict=',redirect_dict
690 for (varname,default) in Module.redirectors:
691 if redirect_dict.has_key(varname):
692 setattr(self,varname,redirect_dict[varname])
693 varnames += [redirect_dict[varname]]
695 setattr(self,varname,default)
696 varnames += [ default ]
697 self.varnames = varnames
698 result = self.parse_spec (specfile,self.varnames)
699 if self.options.debug:
700 print '2st pass parsing done, varnames=',varnames,'result=',result
703 def patch_spec_var (self, patch_dict,define_missing=False):
704 for specfile in self.all_specnames():
705 # record the keys that were changed
706 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
707 newspecfile=specfile+".new"
708 if self.options.verbose:
709 print 'Patching',specfile,'for',patch_dict.keys()
711 new=open(newspecfile,"w")
713 for line in spec.readlines():
714 attempt=Module.matcher_rpm_define.match(line)
716 (define,var,value)=attempt.groups()
717 if var in patch_dict.keys():
718 if self.options.debug:
719 print 'rewriting %s as %s'%(var,patch_dict[var])
720 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
725 for (key,was_changed) in changed.iteritems():
727 if self.options.debug:
728 print 'rewriting missing %s as %s'%(key,patch_dict[key])
729 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
732 os.rename(newspecfile,specfile)
734 # returns all lines until the magic line
735 def unignored_lines (self, logfile):
737 white_line_matcher = re.compile("\A\s*\Z")
738 for logline in file(logfile).readlines():
739 if logline.strip() == Module.svn_magic_line:
741 elif white_line_matcher.match(logline):
744 result.append(logline.strip()+'\n')
747 # creates a copy of the input with only the unignored lines
748 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
750 f.write(self.setting_tag_format%new_tag_name + '\n')
751 for line in self.unignored_lines(filein):
755 def insert_changelog (self, logfile, oldtag, newtag):
756 for specfile in self.all_specnames():
757 newspecfile=specfile+".new"
758 if self.options.verbose:
759 print 'Inserting changelog from %s into %s'%(logfile,specfile)
761 new=open(newspecfile,"w")
762 for line in spec.readlines():
764 if re.compile('%changelog').match(line):
765 dateformat="* %a %b %d %Y"
766 datepart=time.strftime(dateformat)
767 logpart="%s <%s> - %s"%(Module.config['username'],
768 Module.config['email'],
770 new.write(datepart+" "+logpart+"\n")
771 for logline in self.unignored_lines(logfile):
772 new.write("- " + logline)
776 os.rename(newspecfile,specfile)
778 def show_dict (self, spec_dict):
779 if self.options.verbose:
780 for (k,v) in spec_dict.iteritems():
783 def last_tag (self, spec_dict):
785 return "%s-%s" % (spec_dict[self.module_version_varname],
786 spec_dict[self.module_taglevel_varname])
788 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
790 def tag_name (self, spec_dict, old_svn_name=False):
791 base_tag_name = self.name
793 base_tag_name = git_to_svn_name(self.name)
794 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
797 ##############################
798 # using fine_grain means replacing only those instances that currently refer to this tag
799 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
800 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
801 newtagsfile=tagsfile+".new"
803 new=open(newtagsfile,"w")
806 # fine-grain : replace those lines that refer to oldname
808 if self.options.verbose:
809 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
810 matcher=re.compile("^(.*)%s(.*)"%oldname)
811 for line in tags.readlines():
812 if not matcher.match(line):
815 (begin,end)=matcher.match(line).groups()
816 new.write(begin+newname+end+"\n")
818 # brute-force : change uncommented lines that define <module>-SVNPATH
820 if self.options.verbose:
821 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
822 pattern="\A\s*(?P<make_name>[^\s]+)-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
824 matcher_module=re.compile(pattern)
825 for line in tags.readlines():
826 attempt=matcher_module.match(line)
828 if line.find("-GITPATH") >= 0:
829 modulepath = "%s-GITPATH"%(attempt.group('make_name'))
830 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
832 modulepath = "%s-SVNPATH"%(attempt.group('make_name'))
833 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
834 if self.options.verbose:
835 print ' ' + modulepath,
836 new.write(replacement)
842 os.rename(newtagsfile,tagsfile)
843 if self.options.verbose: print "%d changes"%matches
846 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
847 if self.options.verbose:
848 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
850 found_tagname = tagname
851 found = self.repository.tag_exists(tagname)
852 if not found and old_svn_tag_name:
853 if self.options.verbose:
855 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
856 found = self.repository.tag_exists(old_svn_tag_name)
858 found_tagname = old_svn_tag_name
860 if (found and need_it) or (not found and not need_it):
861 if self.options.verbose:
863 if found: print "- found"
864 else: print "- not found"
866 if self.options.verbose:
869 raise Exception, "tag (%s) is already there" % tagname
871 raise Exception, "can not find required tag (%s)" % tagname
876 ##############################
878 self.init_module_dir()
879 self.revert_module_dir()
880 self.update_module_dir()
882 spec_dict = self.spec_dict()
883 self.show_dict(spec_dict)
886 old_tag_name = self.tag_name(spec_dict)
887 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
889 if (self.options.new_version):
890 # new version set on command line
891 spec_dict[self.module_version_varname] = self.options.new_version
892 spec_dict[self.module_taglevel_varname] = 0
895 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
896 spec_dict[self.module_taglevel_varname] = new_taglevel
898 new_tag_name = self.tag_name(spec_dict)
901 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
902 new_tag_name = self.check_tag(new_tag_name, need_it=False)
905 diff_output = self.repository.diff_with_tag(old_tag_name)
906 if len(diff_output) == 0:
907 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
910 # side effect in trunk's specfile
911 self.patch_spec_var(spec_dict)
913 # prepare changelog file
914 # we use the standard subversion magic string (see svn_magic_line)
915 # so we can provide useful information, such as version numbers and diff
917 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
918 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
919 setting_tag_line=Module.setting_tag_format%new_tag_name
920 file(changelog,"w").write("""
923 Please write a changelog for this new tag in the section above
924 """%(Module.svn_magic_line,setting_tag_line))
926 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
927 file(changelog,"a").write('DIFF=========\n' + diff_output)
929 if self.options.debug:
933 self.run("%s %s"%(self.options.editor,changelog))
934 # strip magic line in second file - looks like svn has changed its magic line with 1.6
935 # so we do the job ourselves
936 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
937 # insert changelog in spec
938 if self.options.changelog:
939 self.insert_changelog (changelog,old_tag_name,new_tag_name)
942 build_path = os.path.join(self.options.workdir,
943 Module.config['build'])
944 build = Repository(build_path, self.options)
945 if self.options.build_branch:
946 build.to_branch(self.options.build_branch)
947 if not build.is_clean():
950 tagsfiles=glob(build.path+"/*-tags*.mk")
951 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
955 for tagsfile in tagsfiles:
956 status=tagsdict[tagsfile]
957 basename=os.path.basename(tagsfile)
958 print ".................... Dealing with %s"%basename
959 while tagsdict[tagsfile] == 'todo' :
960 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
961 [ ('y','es'), ('n', 'ext'), ('f','orce'),
962 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
965 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
967 print 'Done with %s'%os.path.basename(tagsfile)
968 tagsdict[tagsfile]='done'
970 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
972 print build.diff(f=tagsfile)
974 build.revert(f=tagsfile)
976 self.run("cat %s"%tagsfile)
979 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
980 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
981 d: show current diff for this tag file
982 r: revert that tag file
983 c: cat the current tag file
984 n: move to next file"""%locals()
986 if prompt("Want to review changes on tags files",False):
987 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
992 def diff_all_changes():
994 print self.repository.diff()
996 def commit_all_changes(log):
997 self.repository.commit(log)
1000 self.run_prompt("Review module and build", diff_all_changes)
1001 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1002 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1004 if self.options.debug:
1005 print 'Preserving',changelog,'and stripped',changelog_svn
1007 os.unlink(changelog)
1008 os.unlink(changelog_svn)
1011 ##############################
1012 def do_version (self):
1013 self.init_module_dir()
1014 self.revert_module_dir()
1015 self.update_module_dir()
1016 spec_dict = self.spec_dict()
1017 if self.options.www:
1018 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1019 self.last_tag(spec_dict)))
1020 for varname in self.varnames:
1021 if not spec_dict.has_key(varname):
1022 self.html_print ('Could not find %%define for %s'%varname)
1025 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1026 if self.options.verbose:
1027 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1028 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1029 self.html_print_end()
1032 ##############################
1034 self.init_module_dir()
1035 self.revert_module_dir()
1036 self.update_module_dir()
1037 spec_dict = self.spec_dict()
1038 self.show_dict(spec_dict)
1041 tag_name = self.tag_name(spec_dict)
1042 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1045 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1047 if self.options.verbose:
1048 print 'Getting diff'
1049 diff_output = self.repository.diff_with_tag(tag_name)
1051 if self.options.list:
1055 thename=self.friendly_name()
1057 if self.options.www and diff_output:
1058 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1059 thename,self.last_tag(spec_dict),len(diff_output)))
1061 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1062 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1063 self.html_store_pre (diff_output)
1064 elif not self.options.www:
1065 print 'x'*30,'module',thename
1066 print 'x'*20,'<',tag_name
1067 print 'x'*20,'>',thename
1070 ##############################
1071 # store and restitute html fragments
1073 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1076 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1079 def html_quote (text):
1080 return text.replace('&','&').replace('<','<').replace('>','>')
1082 # only the fake error module has multiple titles
1083 def html_store_title (self, title):
1084 if not hasattr(self,'titles'): self.titles=[]
1085 self.titles.append(title)
1087 def html_store_raw (self, html):
1088 if not hasattr(self,'body'): self.body=''
1091 def html_store_pre (self, text):
1092 if not hasattr(self,'body'): self.body=''
1093 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1095 def html_print (self, txt):
1096 if not self.options.www:
1099 if not hasattr(self,'in_list') or not self.in_list:
1100 self.html_store_raw('<ul>')
1102 self.html_store_raw('<li>'+txt+'</li>')
1104 def html_print_end (self):
1105 if self.options.www:
1106 self.html_store_raw ('</ul>')
1109 def html_dump_header(title):
1110 nowdate=time.strftime("%Y-%m-%d")
1111 nowtime=time.strftime("%H:%M (%Z)")
1112 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1113 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1116 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1117 <style type="text/css">
1118 body { font-family:georgia, serif; }
1119 h1 {font-size: large; }
1120 p.title {font-size: x-large; }
1121 span.error {text-weight:bold; color: red; }
1125 <p class='title'> %s - status on %s at %s</p>
1127 """%(title,title,nowdate,nowtime)
1130 def html_dump_middle():
1134 def html_dump_footer():
1135 print "</body></html"
1137 def html_dump_toc(self):
1138 if hasattr(self,'titles'):
1139 for title in self.titles:
1140 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1142 def html_dump_body(self):
1143 if hasattr(self,'titles'):
1144 for title in self.titles:
1145 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1146 if hasattr(self,'body'):
1148 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1151 ##############################
1154 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1156 module-tools : a set of tools to manage subversion tags and specfile
1157 requires the specfile to either
1158 * define *version* and *taglevel*
1160 * define redirection variables module_version_varname / module_taglevel_varname
1162 by default, the trunk of modules is taken into account
1163 in this case, just mention the module name as <module_desc>
1165 if you wish to work on a branch rather than on the trunk,
1166 you can use something like e.g. Mom:2.1 as <module_desc>
1168 release_usage="""Usage: %prog [options] tag1 .. tagn
1169 Extract release notes from the changes in specfiles between several build tags, latest first
1171 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1172 You can refer to a (build) branch by prepending a colon, like in
1173 release-changelog :4.2 4.2-rc25
1174 You can refer to the build trunk by just mentioning 'trunk', e.g.
1175 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1177 common_usage="""More help:
1178 see http://svn.planet-lab.org/wiki/ModuleTools"""
1181 'list' : "displays a list of available tags or branches",
1182 'version' : "check latest specfile and print out details",
1183 'diff' : "show difference between module (trunk or branch) and latest tag",
1184 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1185 create new tag and and monitor its adoption in build/*-tags*.mk""",
1186 'branch' : """create a branch for this module, from the latest tag on the trunk,
1187 and change trunk's version number to reflect the new branch name;
1188 you can specify the new branch name by using module:branch""",
1189 'sync' : """create a tag from the module
1190 this is a last resort option, mostly for repairs""",
1191 'changelog' : """extract changelog between build tags
1192 expected arguments are a list of tags""",
1195 silent_modes = ['list']
1196 release_modes = ['changelog']
1199 def optparse_list (option, opt, value, parser):
1201 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1203 setattr(parser.values,option.dest,value.split())
1208 for function in Main.modes.keys():
1209 if sys.argv[0].find(function) >= 0:
1213 print "Unsupported command",sys.argv[0]
1214 print "Supported commands:" + " ".join(Main.modes.keys())
1217 if mode not in Main.release_modes:
1218 usage = Main.module_usage
1219 usage += Main.common_usage
1220 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1222 usage = Main.release_usage
1223 usage += Main.common_usage
1225 parser=OptionParser(usage=usage)
1227 if mode == "tag" or mode == 'branch':
1228 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1229 help="set new version and reset taglevel to 0")
1231 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1232 help="do not update changelog section in specfile when tagging")
1233 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1234 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1235 if mode == "tag" or mode == "sync" :
1236 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1237 help="specify editor")
1239 if mode in ["diff","version"] :
1240 parser.add_option("-W","--www", action="store", dest="www", default=False,
1241 help="export diff in html format, e.g. -W trunk")
1244 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1245 help="just list modules that exhibit differences")
1247 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1248 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1249 help="run on all modules as found in %s"%default_modules_list)
1250 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1251 help="run on all modules found in specified file")
1252 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1253 help="dry run - shell commands are only displayed")
1254 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1255 default=[], nargs=1,type="string",
1256 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1257 -- can be set multiple times, or use quotes""")
1259 parser.add_option("-w","--workdir", action="store", dest="workdir",
1260 default="%s/%s"%(os.getenv("HOME"),"modules"),
1261 help="""name for dedicated working dir - defaults to ~/modules
1262 ** THIS MUST NOT ** be your usual working directory""")
1263 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1264 help="skip safety checks, such as svn updates -- use with care")
1266 # default verbosity depending on function - temp
1267 verbose_modes= ['tag', 'sync', 'branch']
1269 if mode not in verbose_modes:
1270 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1271 help="run in verbose mode")
1273 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1274 help="run in quiet (non-verbose) mode")
1275 (options, args) = parser.parse_args()
1277 if not hasattr(options,'dry_run'):
1278 options.dry_run=False
1279 if not hasattr(options,'www'):
1285 if options.all_modules:
1286 options.modules_list=default_modules_list
1287 if options.modules_list:
1288 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1292 Module.init_homedir(options)
1295 modules=[ Module(modname,options) for modname in args ]
1296 # hack: create a dummy Module to store errors/warnings
1297 error_module = Module('__errors__',options)
1299 for module in modules:
1300 if len(args)>1 and mode not in Main.silent_modes:
1302 print '========================================',module.friendly_name()
1303 # call the method called do_<mode>
1304 method=Module.__dict__["do_%s"%mode]
1309 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1310 (module.friendly_name(), str(e))
1311 error_module.html_store_title(title)
1314 traceback.print_exc()
1315 print 'Skipping module %s: '%modname,e
1319 modetitle="Changes to tag in %s"%options.www
1320 elif mode == "version":
1321 modetitle="Latest tags in %s"%options.www
1322 modules.append(error_module)
1323 error_module.html_dump_header(modetitle)
1324 for module in modules:
1325 module.html_dump_toc()
1326 Module.html_dump_middle()
1327 for module in modules:
1328 module.html_dump_body()
1329 Module.html_dump_footer()
1331 ####################
1332 if __name__ == "__main__" :
1335 except KeyboardInterrupt: