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": "vserver-reference",
19 "BootstrapFS": "bootstrapfs",
22 "NodeManager": "nodemanager"
25 def svn_to_git_name(module):
26 if RENAMED_SVN_MODULES.has_key(module):
27 return RENAMED_SVN_MODULES[module]
30 def git_to_svn_name(module):
31 for key in RENAMED_SVN_MODULES:
32 if module == RENAMED_SVN_MODULES[key]:
37 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
38 def prompt (question,default=True,other_choices=[],allow_outside=False):
39 if not isinstance (other_choices,list):
40 other_choices = [ other_choices ]
41 chars = [ c for (c,rest) in other_choices ]
45 if default is True: choices.append('[y]')
46 else : choices.append('y')
48 if default is False: choices.append('[n]')
49 else : choices.append('n')
51 for (char,choice) in other_choices:
53 choices.append("["+char+"]"+choice)
55 choices.append("<"+char+">"+choice)
57 answer=raw_input(question + " " + "/".join(choices) + " ? ")
60 answer=answer[0].lower()
62 if 'y' in chars: return 'y'
65 if 'n' in chars: return 'n'
68 for (char,choice) in other_choices:
73 return prompt(question,default,other_choices)
79 editor = os.environ['EDITOR']
87 def print_fold (line):
88 while len(line) >= fold_length:
89 print line[:fold_length],'\\'
90 line=line[fold_length:]
94 def __init__ (self,command,options):
97 self.tmp="/tmp/command-%d"%os.getpid()
100 if self.options.dry_run:
101 print 'dry_run',self.command
103 if self.options.verbose and self.options.mode not in Main.silent_modes:
104 print '+',self.command
106 return os.system(self.command)
108 def run_silent (self):
109 if self.options.dry_run:
110 print 'dry_run',self.command
112 if self.options.verbose:
113 print '+',self.command,' .. ',
115 retcod=os.system(self.command + " &> " + self.tmp)
117 print "FAILED ! -- out+err below (command was %s)"%self.command
118 os.system("cat " + self.tmp)
119 print "FAILED ! -- end of quoted output"
120 elif self.options.verbose:
126 if self.run_silent() !=0:
127 raise Exception,"Command %s failed"%self.command
129 # returns stdout, like bash's $(mycommand)
130 def output_of (self,with_stderr=False):
131 if self.options.dry_run:
132 print 'dry_run',self.command
133 return 'dry_run output'
134 tmp="/tmp/status-%d"%os.getpid()
135 if self.options.debug:
136 print '+',self.command,' .. ',
145 result=file(tmp).read()
147 if self.options.debug:
155 def __init__(self, path, options):
157 self.options = options
160 return os.path.basename(self.path)
163 out = Command("svn info %s" % self.path, self.options).output_of()
164 for line in out.split('\n'):
165 if line.startswith("URL:"):
166 return line.split()[1].strip()
169 out = Command("svn info %s" % self.path, self.options).output_of()
170 for line in out.split('\n'):
171 if line.startswith("Repository Root:"):
172 root = line.split()[2].strip()
173 return "%s/%s" % (root, self.name())
176 def checkout(cls, remote, local, options, recursive=False):
178 svncommand = "svn co %s %s" % (remote, local)
180 svncommand = "svn co -N %s %s" % (remote, local)
181 Command("rm -rf %s" % local, options).run_silent()
182 Command(svncommand, options).run_fatal()
184 return SvnRepository(local, options)
187 def remote_exists(cls, remote):
188 return os.system("svn list %s &> /dev/null" % remote) == 0
190 def tag_exists(self, tagname):
191 url = "%s/tags/%s" % (self.repo_root(), tagname)
192 return SvnRepository.remote_exists(url)
194 def update(self, subdir="", recursive=True, branch=None):
195 path = os.path.join(self.path, subdir)
197 svncommand = "svn up %s" % path
199 svncommand = "svn up -N %s" % path
200 Command(svncommand, self.options).run_fatal()
202 def commit(self, logfile):
203 # add all new files to the repository
204 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
205 self.path, self.options).output_of()
206 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
208 def to_branch(self, branch):
209 remote = "%s/branches/%s" % (self.repo_root(), branch)
210 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
212 def to_tag(self, tag):
213 remote = "%s/tags/%s" % (self.repo_root(), branch)
214 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
216 def tag(self, tagname, logfile):
217 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
218 self_url = self.url()
219 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
221 def diff(self, f=""):
223 f = os.path.join(self.path, f)
226 return Command("svn diff %s" % f, self.options).output_of(True)
228 def diff_with_tag(self, tagname):
229 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
230 return Command("svn diff %s %s" % (tag_url, self.url()),
231 self.options).output_of(True)
233 def revert(self, f=""):
235 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
238 Command("svn revert %s -R" % self.path, self.options).run_fatal()
239 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
240 self.path, self.options).run_silent()
243 command="svn status %s" % self.path
244 return len(Command(command,self.options).output_of(True)) == 0
247 return os.path.exists(os.path.join(self.path, ".svn"))
253 def __init__(self, path, options):
255 self.options = options
258 return os.path.basename(self.path)
264 c = Command("git remote show origin", self.options)
265 out = self.__run_in_repo(c.output_of)
266 for line in out.split('\n'):
267 if line.strip().startswith("Fetch URL:"):
268 repo = line.split()[2]
271 def checkout(cls, remote, local, options, depth=1):
272 Command("rm -rf %s" % local, options).run_silent()
273 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
274 return GitRepository(local, options)
277 def remote_exists(cls, remote):
278 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
280 def tag_exists(self, tagname):
281 command = 'git tag -l | grep "^%s$"' % tagname
282 c = Command(command, self.options)
283 out = self.__run_in_repo(c.output_of, with_stderr=True)
286 def __run_in_repo(self, fun, *args, **kwargs):
289 ret = fun(*args, **kwargs)
293 def __run_command_in_repo(self, command, ignore_errors=False):
294 c = Command(command, self.options)
296 return self.__run_in_repo(c.output_of)
298 return self.__run_in_repo(c.run_fatal)
300 def update(self, subdir=None, recursive=None, branch="master"):
301 if branch == "master":
302 self.__run_command_in_repo("git checkout %s" % branch)
304 self.__run_command_in_repo("git checkout origin/%s" % branch)
305 self.__run_command_in_repo("git fetch origin --tags")
306 self.__run_command_in_repo("git fetch origin")
307 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
309 def to_branch(self, branch, remote=True):
311 branch = "origin/%s" % branch
312 return self.__run_command_in_repo("git checkout %s" % branch)
314 def to_tag(self, tag):
315 return self.__run_command_in_repo("git checkout %s" % tag)
317 def tag(self, tagname, logfile):
318 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
321 def diff(self, f=""):
322 c = Command("git diff %s" % f, self.options)
323 return self.__run_in_repo(c.output_of, with_stderr=True)
325 def diff_with_tag(self, tagname):
326 c = Command("git diff %s" % tagname, self.options)
327 return self.__run_in_repo(c.output_of, with_stderr=True)
329 def commit(self, logfile):
330 self.__run_command_in_repo("git add .", ignore_errors=True)
331 self.__run_command_in_repo("git add -u", ignore_errors=True)
332 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
333 self.__run_command_in_repo("git push")
334 self.__run_command_in_repo("git push --tags")
336 def revert(self, f=""):
338 self.__run_command_in_repo("git checkout %s" % f)
341 self.__run_command_in_repo("git --no-pager reset --hard")
342 self.__run_command_in_repo("git --no-pager clean -f")
347 s="nothing to commit (working directory clean)"
348 return Command(command, self.options).output_of(True).find(s) >= 0
349 return self.__run_in_repo(check_commit)
352 return os.path.exists(os.path.join(self.path, ".git"))
356 """ Generic repository """
357 supported_repo_types = [SvnRepository, GitRepository]
359 def __init__(self, path, options):
361 self.options = options
362 for repo in self.supported_repo_types:
363 self.repo = repo(self.path, self.options)
364 if self.repo.is_valid():
368 def has_moved_to_git(cls, module, config):
369 module = svn_to_git_name(module)
370 # check if the module is already in Git
371 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
372 return GitRepository.remote_exists(Module.git_remote_dir(module))
376 def remote_exists(cls, remote):
377 for repo in Repository.supported_repo_types:
378 if repo.remote_exists(remote):
382 def __getattr__(self, attr):
383 return getattr(self.repo, attr)
387 # support for tagged module is minimal, and is for the Build class only
390 svn_magic_line="--This line, and those below, will be ignored--"
391 setting_tag_format = "Setting tag %s"
393 redirectors=[ # ('module_name_varname','name'),
394 ('module_version_varname','version'),
395 ('module_taglevel_varname','taglevel'), ]
397 # where to store user's config
398 config_storage="CONFIG"
403 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
404 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
405 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
406 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
407 ("build", "Enter the name of your build module","build"),
408 ('username',"Enter your firstname and lastname for changelogs",""),
409 ("email","Enter your email address for changelogs",""),
413 def prompt_config_option(cls, key, message, default):
414 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
417 def prompt_config (cls):
418 for (key,message,default) in cls.configKeys:
420 while not cls.config[key]:
421 cls.prompt_config_option(key, message, default)
424 # for parsing module spec name:branch
425 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
426 # special form for tagged module - for Build
427 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
429 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
431 def __init__ (self,module_spec,options):
433 attempt=Module.matcher_branch_spec.match(module_spec)
435 self.name=attempt.group('name')
436 self.branch=attempt.group('branch')
438 attempt=Module.matcher_tag_spec.match(module_spec)
440 self.name=attempt.group('name')
441 self.tagname=attempt.group('tagname')
443 self.name=module_spec
445 # when available prefer to use git module name internally
446 self.name = svn_to_git_name(self.name)
449 self.module_dir="%s/%s"%(options.workdir,self.name)
450 self.repository = None
453 def run (self,command):
454 return Command(command,self.options).run()
455 def run_fatal (self,command):
456 return Command(command,self.options).run_fatal()
457 def run_prompt (self,message,fun, *args):
458 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
459 if not self.options.verbose:
461 choice=prompt(message,True,('s','how'))
465 elif choice is False:
466 print 'About to run function:', fun_msg
468 question=message+" - want to run function: " + fun_msg
469 if prompt(question,True):
472 def friendly_name (self):
473 if hasattr(self,'branch'):
474 return "%s:%s"%(self.name,self.branch)
475 elif hasattr(self,'tagname'):
476 return "%s@%s"%(self.name,self.tagname)
481 def git_remote_dir (cls, name):
482 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
485 def svn_remote_dir (cls, name):
486 name = git_to_svn_name(name)
487 svn = cls.config['svnpath']
488 if svn.endswith('/'):
489 return "%s%s" % (svn, name)
490 return "%s/%s" % (svn, name)
492 def svn_selected_remote(self):
493 svn_name = git_to_svn_name(self.name)
494 remote = self.svn_remote_dir(svn_name)
495 if hasattr(self,'branch'):
496 remote = "%s/branches/%s" % (remote, self.branch)
497 elif hasattr(self,'tagname'):
498 remote = "%s/tags/%s" % (remote, self.tagname)
500 remote = "%s/trunk" % remote
505 def init_homedir (cls, options):
506 if options.verbose and options.mode not in Main.silent_modes:
507 print 'Checking for', options.workdir
508 storage="%s/%s"%(options.workdir, cls.config_storage)
509 # sanity check. Either the topdir exists AND we have a config/storage
510 # or topdir does not exist and we create it
511 # to avoid people use their own daily svn repo
512 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
513 print """The directory %s exists and has no CONFIG file
514 If this is your regular working directory, please provide another one as the
515 module-* commands need a fresh working dir. Make sure that you do not use
516 that for other purposes than tagging""" % options.workdir
519 def checkout_build():
520 print "Checking out build module..."
521 remote = cls.git_remote_dir(cls.config['build'])
522 local = os.path.join(options.workdir, cls.config['build'])
523 GitRepository.checkout(remote, local, options, depth=1)
528 for (key,message,default) in Module.configKeys:
529 f.write("%s=%s\n"%(key,Module.config[key]))
532 print 'Stored',storage
533 Command("cat %s"%storage,options).run()
538 for line in f.readlines():
539 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
540 Module.config[key]=value
543 if not os.path.isdir (options.workdir):
544 print "Cannot find",options.workdir,"let's create it"
545 Command("mkdir -p %s" % options.workdir, options).run_silent()
551 # check missing config options
553 for (key,message,default) in cls.configKeys:
554 if not Module.config.has_key(key):
555 print "Configuration changed for module-tools"
556 cls.prompt_config_option(key, message, default)
560 Command("rm -rf %s" % options.workdir, options).run_silent()
561 Command("mkdir -p %s" % options.workdir, options).run_silent()
565 build_dir = os.path.join(options.workdir, cls.config['build'])
566 if not os.path.isdir(build_dir):
569 build = Repository(build_dir, options)
570 if not build.is_clean():
571 print "build module needs a revert"
576 if options.verbose and options.mode not in Main.silent_modes:
577 print '******** Using config'
578 for (key,message,default) in Module.configKeys:
579 print '\t',key,'=',Module.config[key]
581 def init_module_dir (self):
582 if self.options.verbose:
583 print 'Checking for',self.module_dir
585 if not os.path.isdir (self.module_dir):
586 if Repository.has_moved_to_git(self.name, Module.config):
587 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
591 remote = self.svn_selected_remote()
592 self.repository = SvnRepository.checkout(remote,
594 self.options, recursive=False)
596 self.repository = Repository(self.module_dir, self.options)
597 if self.repository.type == "svn":
598 # check if module has moved to git
599 if Repository.has_moved_to_git(self.name, Module.config):
600 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
601 self.init_module_dir()
602 # check if we have the required branch/tag
603 if self.repository.url() != self.svn_selected_remote():
604 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
605 self.init_module_dir()
607 elif self.repository.type == "git":
608 if hasattr(self,'branch'):
609 self.repository.to_branch(self.branch)
610 elif hasattr(self,'tagname'):
611 self.repository.to_tag(self.tagname)
614 raise Exception, 'Cannot find %s - check module name'%self.module_dir
617 def revert_module_dir (self):
618 if self.options.fast_checks:
619 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
621 if self.options.verbose:
622 print 'Checking whether', self.module_dir, 'needs being reverted'
624 if not self.repository.is_clean():
625 self.repository.revert()
627 def update_module_dir (self):
628 if self.options.fast_checks:
629 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
631 if self.options.verbose:
632 print 'Updating', self.module_dir
634 if hasattr(self,'branch'):
635 self.repository.update(branch=self.branch)
636 elif hasattr(self,'tagname'):
637 self.repository.update(branch=self.tagname)
639 self.repository.update()
641 def main_specname (self):
642 attempt="%s/%s.spec"%(self.module_dir,self.name)
643 if os.path.isfile (attempt):
645 pattern1="%s/*.spec"%self.module_dir
646 level1=glob(pattern1)
649 pattern2="%s/*/*.spec"%self.module_dir
650 level2=glob(pattern2)
654 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
656 def all_specnames (self):
657 level1=glob("%s/*.spec" % self.module_dir)
658 if level1: return level1
659 level2=glob("%s/*/*.spec" % self.module_dir)
662 def parse_spec (self, specfile, varnames):
663 if self.options.verbose:
664 print 'Parsing',specfile,
670 for line in f.readlines():
671 attempt=Module.matcher_rpm_define.match(line)
673 (define,var,value)=attempt.groups()
677 if self.options.debug:
678 print 'found',len(result),'keys'
679 for (k,v) in result.iteritems():
683 # stores in self.module_name_varname the rpm variable to be used for the module's name
684 # and the list of these names in self.varnames
685 def spec_dict (self):
686 specfile=self.main_specname()
687 redirector_keys = [ varname for (varname,default) in Module.redirectors]
688 redirect_dict = self.parse_spec(specfile,redirector_keys)
689 if self.options.debug:
690 print '1st pass parsing done, redirect_dict=',redirect_dict
692 for (varname,default) in Module.redirectors:
693 if redirect_dict.has_key(varname):
694 setattr(self,varname,redirect_dict[varname])
695 varnames += [redirect_dict[varname]]
697 setattr(self,varname,default)
698 varnames += [ default ]
699 self.varnames = varnames
700 result = self.parse_spec (specfile,self.varnames)
701 if self.options.debug:
702 print '2st pass parsing done, varnames=',varnames,'result=',result
705 def patch_spec_var (self, patch_dict,define_missing=False):
706 for specfile in self.all_specnames():
707 # record the keys that were changed
708 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
709 newspecfile=specfile+".new"
710 if self.options.verbose:
711 print 'Patching',specfile,'for',patch_dict.keys()
713 new=open(newspecfile,"w")
715 for line in spec.readlines():
716 attempt=Module.matcher_rpm_define.match(line)
718 (define,var,value)=attempt.groups()
719 if var in patch_dict.keys():
720 if self.options.debug:
721 print 'rewriting %s as %s'%(var,patch_dict[var])
722 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
727 for (key,was_changed) in changed.iteritems():
729 if self.options.debug:
730 print 'rewriting missing %s as %s'%(key,patch_dict[key])
731 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
734 os.rename(newspecfile,specfile)
736 # returns all lines until the magic line
737 def unignored_lines (self, logfile):
739 white_line_matcher = re.compile("\A\s*\Z")
740 for logline in file(logfile).readlines():
741 if logline.strip() == Module.svn_magic_line:
743 elif white_line_matcher.match(logline):
746 result.append(logline.strip()+'\n')
749 # creates a copy of the input with only the unignored lines
750 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
752 f.write(self.setting_tag_format%new_tag_name + '\n')
753 for line in self.unignored_lines(filein):
757 def insert_changelog (self, logfile, oldtag, newtag):
758 for specfile in self.all_specnames():
759 newspecfile=specfile+".new"
760 if self.options.verbose:
761 print 'Inserting changelog from %s into %s'%(logfile,specfile)
763 new=open(newspecfile,"w")
764 for line in spec.readlines():
766 if re.compile('%changelog').match(line):
767 dateformat="* %a %b %d %Y"
768 datepart=time.strftime(dateformat)
769 logpart="%s <%s> - %s"%(Module.config['username'],
770 Module.config['email'],
772 new.write(datepart+" "+logpart+"\n")
773 for logline in self.unignored_lines(logfile):
774 new.write("- " + logline)
778 os.rename(newspecfile,specfile)
780 def show_dict (self, spec_dict):
781 if self.options.verbose:
782 for (k,v) in spec_dict.iteritems():
785 def last_tag (self, spec_dict):
787 return "%s-%s" % (spec_dict[self.module_version_varname],
788 spec_dict[self.module_taglevel_varname])
790 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
792 def tag_name (self, spec_dict, old_svn_name=False):
793 base_tag_name = self.name
795 base_tag_name = git_to_svn_name(self.name)
796 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
799 ##############################
800 # using fine_grain means replacing only those instances that currently refer to this tag
801 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
802 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
803 newtagsfile=tagsfile+".new"
805 new=open(newtagsfile,"w")
808 # fine-grain : replace those lines that refer to oldname
810 if self.options.verbose:
811 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
812 matcher=re.compile("^(.*)%s(.*)"%oldname)
813 for line in tags.readlines():
814 if not matcher.match(line):
817 (begin,end)=matcher.match(line).groups()
818 new.write(begin+newname+end+"\n")
820 # brute-force : change uncommented lines that define <module>-SVNPATH
822 if self.options.verbose:
823 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
824 pattern="\A\s*(?P<make_name>[^\s]+)-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
826 matcher_module=re.compile(pattern)
827 for line in tags.readlines():
828 attempt=matcher_module.match(line)
830 if line.find("-GITPATH") >= 0:
831 modulepath = "%s-GITPATH"%(attempt.group('make_name'))
832 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
834 modulepath = "%s-SVNPATH"%(attempt.group('make_name'))
835 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
836 if self.options.verbose:
837 print ' ' + modulepath,
838 new.write(replacement)
844 os.rename(newtagsfile,tagsfile)
845 if self.options.verbose: print "%d changes"%matches
848 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
849 if self.options.verbose:
850 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
852 found_tagname = tagname
853 found = self.repository.tag_exists(tagname)
854 if not found and old_svn_tag_name:
855 if self.options.verbose:
857 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
858 found = self.repository.tag_exists(old_svn_tag_name)
860 found_tagname = old_svn_tag_name
862 if (found and need_it) or (not found and not need_it):
863 if self.options.verbose:
865 if found: print "- found"
866 else: print "- not found"
868 if self.options.verbose:
871 raise Exception, "tag (%s) is already there" % tagname
873 raise Exception, "can not find required tag (%s)" % tagname
878 ##############################
880 self.init_module_dir()
881 self.revert_module_dir()
882 self.update_module_dir()
884 spec_dict = self.spec_dict()
885 self.show_dict(spec_dict)
888 old_tag_name = self.tag_name(spec_dict)
889 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
891 if (self.options.new_version):
892 # new version set on command line
893 spec_dict[self.module_version_varname] = self.options.new_version
894 spec_dict[self.module_taglevel_varname] = 0
897 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
898 spec_dict[self.module_taglevel_varname] = new_taglevel
900 new_tag_name = self.tag_name(spec_dict)
903 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
904 new_tag_name = self.check_tag(new_tag_name, need_it=False)
907 diff_output = self.repository.diff_with_tag(old_tag_name)
908 if len(diff_output) == 0:
909 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
912 # side effect in trunk's specfile
913 self.patch_spec_var(spec_dict)
915 # prepare changelog file
916 # we use the standard subversion magic string (see svn_magic_line)
917 # so we can provide useful information, such as version numbers and diff
919 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
920 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
921 setting_tag_line=Module.setting_tag_format%new_tag_name
922 file(changelog,"w").write("""
925 Please write a changelog for this new tag in the section above
926 """%(Module.svn_magic_line,setting_tag_line))
928 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
929 file(changelog,"a").write('DIFF=========\n' + diff_output)
931 if self.options.debug:
935 self.run("%s %s"%(self.options.editor,changelog))
936 # strip magic line in second file - looks like svn has changed its magic line with 1.6
937 # so we do the job ourselves
938 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
939 # insert changelog in spec
940 if self.options.changelog:
941 self.insert_changelog (changelog,old_tag_name,new_tag_name)
944 build_path = os.path.join(self.options.workdir,
945 Module.config['build'])
946 build = Repository(build_path, self.options)
947 if self.options.build_branch:
948 build.to_branch(self.options.build_branch)
949 if not build.is_clean():
952 tagsfiles=glob(build.path+"/*-tags*.mk")
953 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
957 for tagsfile in tagsfiles:
958 status=tagsdict[tagsfile]
959 basename=os.path.basename(tagsfile)
960 print ".................... Dealing with %s"%basename
961 while tagsdict[tagsfile] == 'todo' :
962 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
963 [ ('y','es'), ('n', 'ext'), ('f','orce'),
964 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
967 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
969 print 'Done with %s'%os.path.basename(tagsfile)
970 tagsdict[tagsfile]='done'
972 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
974 print build.diff(f=tagsfile)
976 build.revert(f=tagsfile)
978 self.run("cat %s"%tagsfile)
981 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
982 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
983 d: show current diff for this tag file
984 r: revert that tag file
985 c: cat the current tag file
986 n: move to next file"""%locals()
988 if prompt("Want to review changes on tags files",False):
989 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
994 def diff_all_changes():
996 print self.repository.diff()
998 def commit_all_changes(log):
999 self.repository.commit(log)
1002 self.run_prompt("Review module and build", diff_all_changes)
1003 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1004 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1006 if self.options.debug:
1007 print 'Preserving',changelog,'and stripped',changelog_svn
1009 os.unlink(changelog)
1010 os.unlink(changelog_svn)
1013 ##############################
1014 def do_version (self):
1015 self.init_module_dir()
1016 self.revert_module_dir()
1017 self.update_module_dir()
1018 spec_dict = self.spec_dict()
1019 if self.options.www:
1020 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1021 self.last_tag(spec_dict)))
1022 for varname in self.varnames:
1023 if not spec_dict.has_key(varname):
1024 self.html_print ('Could not find %%define for %s'%varname)
1027 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1028 if self.options.verbose:
1029 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1030 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1031 self.html_print_end()
1034 ##############################
1036 self.init_module_dir()
1037 self.revert_module_dir()
1038 self.update_module_dir()
1039 spec_dict = self.spec_dict()
1040 self.show_dict(spec_dict)
1043 tag_name = self.tag_name(spec_dict)
1044 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1047 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1049 if self.options.verbose:
1050 print 'Getting diff'
1051 diff_output = self.repository.diff_with_tag(tag_name)
1053 if self.options.list:
1057 thename=self.friendly_name()
1059 if self.options.www and diff_output:
1060 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1061 thename,self.last_tag(spec_dict),len(diff_output)))
1063 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1064 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1065 self.html_store_pre (diff_output)
1066 elif not self.options.www:
1067 print 'x'*30,'module',thename
1068 print 'x'*20,'<',tag_name
1069 print 'x'*20,'>',thename
1072 ##############################
1073 # store and restitute html fragments
1075 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1078 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1081 def html_quote (text):
1082 return text.replace('&','&').replace('<','<').replace('>','>')
1084 # only the fake error module has multiple titles
1085 def html_store_title (self, title):
1086 if not hasattr(self,'titles'): self.titles=[]
1087 self.titles.append(title)
1089 def html_store_raw (self, html):
1090 if not hasattr(self,'body'): self.body=''
1093 def html_store_pre (self, text):
1094 if not hasattr(self,'body'): self.body=''
1095 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1097 def html_print (self, txt):
1098 if not self.options.www:
1101 if not hasattr(self,'in_list') or not self.in_list:
1102 self.html_store_raw('<ul>')
1104 self.html_store_raw('<li>'+txt+'</li>')
1106 def html_print_end (self):
1107 if self.options.www:
1108 self.html_store_raw ('</ul>')
1111 def html_dump_header(title):
1112 nowdate=time.strftime("%Y-%m-%d")
1113 nowtime=time.strftime("%H:%M (%Z)")
1114 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1115 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1118 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1119 <style type="text/css">
1120 body { font-family:georgia, serif; }
1121 h1 {font-size: large; }
1122 p.title {font-size: x-large; }
1123 span.error {text-weight:bold; color: red; }
1127 <p class='title'> %s - status on %s at %s</p>
1129 """%(title,title,nowdate,nowtime)
1132 def html_dump_middle():
1136 def html_dump_footer():
1137 print "</body></html"
1139 def html_dump_toc(self):
1140 if hasattr(self,'titles'):
1141 for title in self.titles:
1142 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1144 def html_dump_body(self):
1145 if hasattr(self,'titles'):
1146 for title in self.titles:
1147 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1148 if hasattr(self,'body'):
1150 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1153 ##############################
1156 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1158 module-tools : a set of tools to manage subversion tags and specfile
1159 requires the specfile to either
1160 * define *version* and *taglevel*
1162 * define redirection variables module_version_varname / module_taglevel_varname
1164 by default, the trunk of modules is taken into account
1165 in this case, just mention the module name as <module_desc>
1167 if you wish to work on a branch rather than on the trunk,
1168 you can use something like e.g. Mom:2.1 as <module_desc>
1170 release_usage="""Usage: %prog [options] tag1 .. tagn
1171 Extract release notes from the changes in specfiles between several build tags, latest first
1173 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1174 You can refer to a (build) branch by prepending a colon, like in
1175 release-changelog :4.2 4.2-rc25
1176 You can refer to the build trunk by just mentioning 'trunk', e.g.
1177 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1179 common_usage="""More help:
1180 see http://svn.planet-lab.org/wiki/ModuleTools"""
1183 'list' : "displays a list of available tags or branches",
1184 'version' : "check latest specfile and print out details",
1185 'diff' : "show difference between module (trunk or branch) and latest tag",
1186 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1187 create new tag and and monitor its adoption in build/*-tags*.mk""",
1188 'branch' : """create a branch for this module, from the latest tag on the trunk,
1189 and change trunk's version number to reflect the new branch name;
1190 you can specify the new branch name by using module:branch""",
1191 'sync' : """create a tag from the module
1192 this is a last resort option, mostly for repairs""",
1193 'changelog' : """extract changelog between build tags
1194 expected arguments are a list of tags""",
1197 silent_modes = ['list']
1198 release_modes = ['changelog']
1201 def optparse_list (option, opt, value, parser):
1203 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1205 setattr(parser.values,option.dest,value.split())
1210 for function in Main.modes.keys():
1211 if sys.argv[0].find(function) >= 0:
1215 print "Unsupported command",sys.argv[0]
1216 print "Supported commands:" + " ".join(Main.modes.keys())
1219 if mode not in Main.release_modes:
1220 usage = Main.module_usage
1221 usage += Main.common_usage
1222 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1224 usage = Main.release_usage
1225 usage += Main.common_usage
1227 parser=OptionParser(usage=usage)
1229 if mode == "tag" or mode == 'branch':
1230 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1231 help="set new version and reset taglevel to 0")
1233 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1234 help="do not update changelog section in specfile when tagging")
1235 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1236 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1237 if mode == "tag" or mode == "sync" :
1238 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1239 help="specify editor")
1241 if mode in ["diff","version"] :
1242 parser.add_option("-W","--www", action="store", dest="www", default=False,
1243 help="export diff in html format, e.g. -W trunk")
1246 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1247 help="just list modules that exhibit differences")
1249 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1250 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1251 help="run on all modules as found in %s"%default_modules_list)
1252 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1253 help="run on all modules found in specified file")
1254 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1255 help="dry run - shell commands are only displayed")
1256 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1257 default=[], nargs=1,type="string",
1258 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1259 -- can be set multiple times, or use quotes""")
1261 parser.add_option("-w","--workdir", action="store", dest="workdir",
1262 default="%s/%s"%(os.getenv("HOME"),"modules"),
1263 help="""name for dedicated working dir - defaults to ~/modules
1264 ** THIS MUST NOT ** be your usual working directory""")
1265 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1266 help="skip safety checks, such as svn updates -- use with care")
1268 # default verbosity depending on function - temp
1269 verbose_modes= ['tag', 'sync', 'branch']
1271 if mode not in verbose_modes:
1272 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1273 help="run in verbose mode")
1275 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1276 help="run in quiet (non-verbose) mode")
1277 (options, args) = parser.parse_args()
1279 if not hasattr(options,'dry_run'):
1280 options.dry_run=False
1281 if not hasattr(options,'www'):
1287 if options.all_modules:
1288 options.modules_list=default_modules_list
1289 if options.modules_list:
1290 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1294 Module.init_homedir(options)
1297 modules=[ Module(modname,options) for modname in args ]
1298 # hack: create a dummy Module to store errors/warnings
1299 error_module = Module('__errors__',options)
1301 for module in modules:
1302 if len(args)>1 and mode not in Main.silent_modes:
1304 print '========================================',module.friendly_name()
1305 # call the method called do_<mode>
1306 method=Module.__dict__["do_%s"%mode]
1311 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1312 (module.friendly_name(), str(e))
1313 error_module.html_store_title(title)
1316 traceback.print_exc()
1317 print 'Skipping module %s: '%modname,e
1321 modetitle="Changes to tag in %s"%options.www
1322 elif mode == "version":
1323 modetitle="Latest tags in %s"%options.www
1324 modules.append(error_module)
1325 error_module.html_dump_header(modetitle)
1326 for module in modules:
1327 module.html_dump_toc()
1328 Module.html_dump_middle()
1329 for module in modules:
1330 module.html_dump_body()
1331 Module.html_dump_footer()
1333 ####################
1334 if __name__ == "__main__" :
1337 except KeyboardInterrupt: