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"
23 "NodeUpdate": "nodeupdate"
26 def svn_to_git_name(module):
27 if RENAMED_SVN_MODULES.has_key(module):
28 return RENAMED_SVN_MODULES[module]
31 def git_to_svn_name(module):
32 for key in RENAMED_SVN_MODULES:
33 if module == RENAMED_SVN_MODULES[key]:
38 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
39 def prompt (question,default=True,other_choices=[],allow_outside=False):
40 if not isinstance (other_choices,list):
41 other_choices = [ other_choices ]
42 chars = [ c for (c,rest) in other_choices ]
46 if default is True: choices.append('[y]')
47 else : choices.append('y')
49 if default is False: choices.append('[n]')
50 else : choices.append('n')
52 for (char,choice) in other_choices:
54 choices.append("["+char+"]"+choice)
56 choices.append("<"+char+">"+choice)
58 answer=raw_input(question + " " + "/".join(choices) + " ? ")
61 answer=answer[0].lower()
63 if 'y' in chars: return 'y'
66 if 'n' in chars: return 'n'
69 for (char,choice) in other_choices:
74 return prompt(question,default,other_choices)
80 editor = os.environ['EDITOR']
88 def print_fold (line):
89 while len(line) >= fold_length:
90 print line[:fold_length],'\\'
91 line=line[fold_length:]
95 def __init__ (self,command,options):
98 self.tmp="/tmp/command-%d"%os.getpid()
101 if self.options.dry_run:
102 print 'dry_run',self.command
104 if self.options.verbose and self.options.mode not in Main.silent_modes:
105 print '+',self.command
107 return os.system(self.command)
109 def run_silent (self):
110 if self.options.dry_run:
111 print 'dry_run',self.command
113 if self.options.verbose:
114 print '+',self.command,' .. ',
116 retcod=os.system(self.command + " &> " + self.tmp)
118 print "FAILED ! -- out+err below (command was %s)"%self.command
119 os.system("cat " + self.tmp)
120 print "FAILED ! -- end of quoted output"
121 elif self.options.verbose:
127 if self.run_silent() !=0:
128 raise Exception,"Command %s failed"%self.command
130 # returns stdout, like bash's $(mycommand)
131 def output_of (self,with_stderr=False):
132 if self.options.dry_run:
133 print 'dry_run',self.command
134 return 'dry_run output'
135 tmp="/tmp/status-%d"%os.getpid()
136 if self.options.debug:
137 print '+',self.command,' .. ',
146 result=file(tmp).read()
148 if self.options.debug:
156 def __init__(self, path, options):
158 self.options = options
161 return os.path.basename(self.path)
164 out = Command("svn info %s" % self.path, self.options).output_of()
165 for line in out.split('\n'):
166 if line.startswith("URL:"):
167 return line.split()[1].strip()
170 out = Command("svn info %s" % self.path, self.options).output_of()
171 for line in out.split('\n'):
172 if line.startswith("Repository Root:"):
173 root = line.split()[2].strip()
174 return "%s/%s" % (root, self.name())
177 def checkout(cls, remote, local, options, recursive=False):
179 svncommand = "svn co %s %s" % (remote, local)
181 svncommand = "svn co -N %s %s" % (remote, local)
182 Command("rm -rf %s" % local, options).run_silent()
183 Command(svncommand, options).run_fatal()
185 return SvnRepository(local, options)
188 def remote_exists(cls, remote):
189 return os.system("svn list %s &> /dev/null" % remote) == 0
191 def tag_exists(self, tagname):
192 url = "%s/tags/%s" % (self.repo_root(), tagname)
193 return SvnRepository.remote_exists(url)
195 def update(self, subdir="", recursive=True, branch=None):
196 path = os.path.join(self.path, subdir)
198 svncommand = "svn up %s" % path
200 svncommand = "svn up -N %s" % path
201 Command(svncommand, self.options).run_fatal()
203 def commit(self, logfile):
204 # add all new files to the repository
205 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
206 self.path, self.options).output_of()
207 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
209 def to_branch(self, branch):
210 remote = "%s/branches/%s" % (self.repo_root(), branch)
211 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
213 def to_tag(self, tag):
214 remote = "%s/tags/%s" % (self.repo_root(), branch)
215 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
217 def tag(self, tagname, logfile):
218 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
219 self_url = self.url()
220 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
222 def diff(self, f=""):
224 f = os.path.join(self.path, f)
227 return Command("svn diff %s" % f, self.options).output_of(True)
229 def diff_with_tag(self, tagname):
230 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
231 return Command("svn diff %s %s" % (tag_url, self.url()),
232 self.options).output_of(True)
234 def revert(self, f=""):
236 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
239 Command("svn revert %s -R" % self.path, self.options).run_fatal()
240 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
241 self.path, self.options).run_silent()
244 command="svn status %s" % self.path
245 return len(Command(command,self.options).output_of(True)) == 0
248 return os.path.exists(os.path.join(self.path, ".svn"))
254 def __init__(self, path, options):
256 self.options = options
259 return os.path.basename(self.path)
265 c = Command("git remote show origin", self.options)
266 out = self.__run_in_repo(c.output_of)
267 for line in out.split('\n'):
268 if line.strip().startswith("Fetch URL:"):
269 repo = line.split()[2]
272 def checkout(cls, remote, local, options, depth=1):
273 Command("rm -rf %s" % local, options).run_silent()
274 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
275 return GitRepository(local, options)
278 def remote_exists(cls, remote):
279 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
281 def tag_exists(self, tagname):
282 command = 'git tag -l | grep "^%s$"' % tagname
283 c = Command(command, self.options)
284 out = self.__run_in_repo(c.output_of, with_stderr=True)
287 def __run_in_repo(self, fun, *args, **kwargs):
290 ret = fun(*args, **kwargs)
294 def __run_command_in_repo(self, command, ignore_errors=False):
295 c = Command(command, self.options)
297 return self.__run_in_repo(c.output_of)
299 return self.__run_in_repo(c.run_fatal)
301 def update(self, subdir=None, recursive=None, branch="master"):
302 if branch == "master":
303 self.__run_command_in_repo("git checkout %s" % branch)
305 self.__run_command_in_repo("git checkout origin/%s" % branch)
306 self.__run_command_in_repo("git fetch origin --tags")
307 self.__run_command_in_repo("git fetch origin")
308 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
310 def to_branch(self, branch, remote=True):
312 branch = "origin/%s" % branch
313 return self.__run_command_in_repo("git checkout %s" % branch)
315 def to_tag(self, tag):
316 return self.__run_command_in_repo("git checkout %s" % tag)
318 def tag(self, tagname, logfile):
319 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
322 def diff(self, f=""):
323 c = Command("git diff %s" % f, self.options)
324 return self.__run_in_repo(c.output_of, with_stderr=True)
326 def diff_with_tag(self, tagname):
327 c = Command("git diff %s" % tagname, self.options)
328 return self.__run_in_repo(c.output_of, with_stderr=True)
330 def commit(self, logfile):
331 self.__run_command_in_repo("git add .", ignore_errors=True)
332 self.__run_command_in_repo("git add -u", ignore_errors=True)
333 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
334 self.__run_command_in_repo("git push")
335 self.__run_command_in_repo("git push --tags")
337 def revert(self, f=""):
339 self.__run_command_in_repo("git checkout %s" % f)
342 self.__run_command_in_repo("git --no-pager reset --hard")
343 self.__run_command_in_repo("git --no-pager clean -f")
348 s="nothing to commit (working directory clean)"
349 return Command(command, self.options).output_of(True).find(s) >= 0
350 return self.__run_in_repo(check_commit)
353 return os.path.exists(os.path.join(self.path, ".git"))
357 """ Generic repository """
358 supported_repo_types = [SvnRepository, GitRepository]
360 def __init__(self, path, options):
362 self.options = options
363 for repo in self.supported_repo_types:
364 self.repo = repo(self.path, self.options)
365 if self.repo.is_valid():
369 def has_moved_to_git(cls, module, config):
370 module = svn_to_git_name(module)
371 # check if the module is already in Git
372 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
373 return GitRepository.remote_exists(Module.git_remote_dir(module))
377 def remote_exists(cls, remote):
378 for repo in Repository.supported_repo_types:
379 if repo.remote_exists(remote):
383 def __getattr__(self, attr):
384 return getattr(self.repo, attr)
388 # support for tagged module is minimal, and is for the Build class only
391 svn_magic_line="--This line, and those below, will be ignored--"
392 setting_tag_format = "Setting tag %s"
394 redirectors=[ # ('module_name_varname','name'),
395 ('module_version_varname','version'),
396 ('module_taglevel_varname','taglevel'), ]
398 # where to store user's config
399 config_storage="CONFIG"
404 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
405 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
406 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
407 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
408 ("build", "Enter the name of your build module","build"),
409 ('username',"Enter your firstname and lastname for changelogs",""),
410 ("email","Enter your email address for changelogs",""),
414 def prompt_config_option(cls, key, message, default):
415 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
418 def prompt_config (cls):
419 for (key,message,default) in cls.configKeys:
421 while not cls.config[key]:
422 cls.prompt_config_option(key, message, default)
425 # for parsing module spec name:branch
426 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
427 # special form for tagged module - for Build
428 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
430 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
432 def __init__ (self,module_spec,options):
434 attempt=Module.matcher_branch_spec.match(module_spec)
436 self.name=attempt.group('name')
437 self.branch=attempt.group('branch')
439 attempt=Module.matcher_tag_spec.match(module_spec)
441 self.name=attempt.group('name')
442 self.tagname=attempt.group('tagname')
444 self.name=module_spec
446 # when available prefer to use git module name internally
447 self.name = svn_to_git_name(self.name)
450 self.module_dir="%s/%s"%(options.workdir,self.name)
451 self.repository = None
454 def run (self,command):
455 return Command(command,self.options).run()
456 def run_fatal (self,command):
457 return Command(command,self.options).run_fatal()
458 def run_prompt (self,message,fun, *args):
459 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
460 if not self.options.verbose:
462 choice=prompt(message,True,('s','how'))
466 elif choice is False:
467 print 'About to run function:', fun_msg
469 question=message+" - want to run function: " + fun_msg
470 if prompt(question,True):
473 def friendly_name (self):
474 if hasattr(self,'branch'):
475 return "%s:%s"%(self.name,self.branch)
476 elif hasattr(self,'tagname'):
477 return "%s@%s"%(self.name,self.tagname)
482 def git_remote_dir (cls, name):
483 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
486 def svn_remote_dir (cls, name):
487 name = git_to_svn_name(name)
488 svn = cls.config['svnpath']
489 if svn.endswith('/'):
490 return "%s%s" % (svn, name)
491 return "%s/%s" % (svn, name)
493 def svn_selected_remote(self):
494 svn_name = git_to_svn_name(self.name)
495 remote = self.svn_remote_dir(svn_name)
496 if hasattr(self,'branch'):
497 remote = "%s/branches/%s" % (remote, self.branch)
498 elif hasattr(self,'tagname'):
499 remote = "%s/tags/%s" % (remote, self.tagname)
501 remote = "%s/trunk" % remote
506 def init_homedir (cls, options):
507 if options.verbose and options.mode not in Main.silent_modes:
508 print 'Checking for', options.workdir
509 storage="%s/%s"%(options.workdir, cls.config_storage)
510 # sanity check. Either the topdir exists AND we have a config/storage
511 # or topdir does not exist and we create it
512 # to avoid people use their own daily svn repo
513 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
514 print """The directory %s exists and has no CONFIG file
515 If this is your regular working directory, please provide another one as the
516 module-* commands need a fresh working dir. Make sure that you do not use
517 that for other purposes than tagging""" % options.workdir
520 def checkout_build():
521 print "Checking out build module..."
522 remote = cls.git_remote_dir(cls.config['build'])
523 local = os.path.join(options.workdir, cls.config['build'])
524 GitRepository.checkout(remote, local, options, depth=1)
529 for (key,message,default) in Module.configKeys:
530 f.write("%s=%s\n"%(key,Module.config[key]))
533 print 'Stored',storage
534 Command("cat %s"%storage,options).run()
539 for line in f.readlines():
540 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
541 Module.config[key]=value
544 if not os.path.isdir (options.workdir):
545 print "Cannot find",options.workdir,"let's create it"
546 Command("mkdir -p %s" % options.workdir, options).run_silent()
552 # check missing config options
554 for (key,message,default) in cls.configKeys:
555 if not Module.config.has_key(key):
556 print "Configuration changed for module-tools"
557 cls.prompt_config_option(key, message, default)
561 Command("rm -rf %s" % options.workdir, options).run_silent()
562 Command("mkdir -p %s" % options.workdir, options).run_silent()
566 build_dir = os.path.join(options.workdir, cls.config['build'])
567 if not os.path.isdir(build_dir):
570 build = Repository(build_dir, options)
571 if not build.is_clean():
572 print "build module needs a revert"
577 if options.verbose and options.mode not in Main.silent_modes:
578 print '******** Using config'
579 for (key,message,default) in Module.configKeys:
580 print '\t',key,'=',Module.config[key]
582 def init_module_dir (self):
583 if self.options.verbose:
584 print 'Checking for',self.module_dir
586 if not os.path.isdir (self.module_dir):
587 if Repository.has_moved_to_git(self.name, Module.config):
588 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
592 remote = self.svn_selected_remote()
593 self.repository = SvnRepository.checkout(remote,
595 self.options, recursive=False)
597 self.repository = Repository(self.module_dir, self.options)
598 if self.repository.type == "svn":
599 # check if module has moved to git
600 if Repository.has_moved_to_git(self.name, Module.config):
601 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
602 self.init_module_dir()
603 # check if we have the required branch/tag
604 if self.repository.url() != self.svn_selected_remote():
605 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
606 self.init_module_dir()
608 elif self.repository.type == "git":
609 if hasattr(self,'branch'):
610 self.repository.to_branch(self.branch)
611 elif hasattr(self,'tagname'):
612 self.repository.to_tag(self.tagname)
615 raise Exception, 'Cannot find %s - check module name'%self.module_dir
618 def revert_module_dir (self):
619 if self.options.fast_checks:
620 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
622 if self.options.verbose:
623 print 'Checking whether', self.module_dir, 'needs being reverted'
625 if not self.repository.is_clean():
626 self.repository.revert()
628 def update_module_dir (self):
629 if self.options.fast_checks:
630 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
632 if self.options.verbose:
633 print 'Updating', self.module_dir
635 if hasattr(self,'branch'):
636 self.repository.update(branch=self.branch)
637 elif hasattr(self,'tagname'):
638 self.repository.update(branch=self.tagname)
640 self.repository.update()
642 def main_specname (self):
643 attempt="%s/%s.spec"%(self.module_dir,self.name)
644 if os.path.isfile (attempt):
646 pattern1="%s/*.spec"%self.module_dir
647 level1=glob(pattern1)
650 pattern2="%s/*/*.spec"%self.module_dir
651 level2=glob(pattern2)
655 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
657 def all_specnames (self):
658 level1=glob("%s/*.spec" % self.module_dir)
659 if level1: return level1
660 level2=glob("%s/*/*.spec" % self.module_dir)
663 def parse_spec (self, specfile, varnames):
664 if self.options.verbose:
665 print 'Parsing',specfile,
671 for line in f.readlines():
672 attempt=Module.matcher_rpm_define.match(line)
674 (define,var,value)=attempt.groups()
678 if self.options.debug:
679 print 'found',len(result),'keys'
680 for (k,v) in result.iteritems():
684 # stores in self.module_name_varname the rpm variable to be used for the module's name
685 # and the list of these names in self.varnames
686 def spec_dict (self):
687 specfile=self.main_specname()
688 redirector_keys = [ varname for (varname,default) in Module.redirectors]
689 redirect_dict = self.parse_spec(specfile,redirector_keys)
690 if self.options.debug:
691 print '1st pass parsing done, redirect_dict=',redirect_dict
693 for (varname,default) in Module.redirectors:
694 if redirect_dict.has_key(varname):
695 setattr(self,varname,redirect_dict[varname])
696 varnames += [redirect_dict[varname]]
698 setattr(self,varname,default)
699 varnames += [ default ]
700 self.varnames = varnames
701 result = self.parse_spec (specfile,self.varnames)
702 if self.options.debug:
703 print '2st pass parsing done, varnames=',varnames,'result=',result
706 def patch_spec_var (self, patch_dict,define_missing=False):
707 for specfile in self.all_specnames():
708 # record the keys that were changed
709 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
710 newspecfile=specfile+".new"
711 if self.options.verbose:
712 print 'Patching',specfile,'for',patch_dict.keys()
714 new=open(newspecfile,"w")
716 for line in spec.readlines():
717 attempt=Module.matcher_rpm_define.match(line)
719 (define,var,value)=attempt.groups()
720 if var in patch_dict.keys():
721 if self.options.debug:
722 print 'rewriting %s as %s'%(var,patch_dict[var])
723 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
728 for (key,was_changed) in changed.iteritems():
730 if self.options.debug:
731 print 'rewriting missing %s as %s'%(key,patch_dict[key])
732 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
735 os.rename(newspecfile,specfile)
737 # returns all lines until the magic line
738 def unignored_lines (self, logfile):
740 white_line_matcher = re.compile("\A\s*\Z")
741 for logline in file(logfile).readlines():
742 if logline.strip() == Module.svn_magic_line:
744 elif white_line_matcher.match(logline):
747 result.append(logline.strip()+'\n')
750 # creates a copy of the input with only the unignored lines
751 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
753 f.write(self.setting_tag_format%new_tag_name + '\n')
754 for line in self.unignored_lines(filein):
758 def insert_changelog (self, logfile, oldtag, newtag):
759 for specfile in self.all_specnames():
760 newspecfile=specfile+".new"
761 if self.options.verbose:
762 print 'Inserting changelog from %s into %s'%(logfile,specfile)
764 new=open(newspecfile,"w")
765 for line in spec.readlines():
767 if re.compile('%changelog').match(line):
768 dateformat="* %a %b %d %Y"
769 datepart=time.strftime(dateformat)
770 logpart="%s <%s> - %s"%(Module.config['username'],
771 Module.config['email'],
773 new.write(datepart+" "+logpart+"\n")
774 for logline in self.unignored_lines(logfile):
775 new.write("- " + logline)
779 os.rename(newspecfile,specfile)
781 def show_dict (self, spec_dict):
782 if self.options.verbose:
783 for (k,v) in spec_dict.iteritems():
786 def last_tag (self, spec_dict):
788 return "%s-%s" % (spec_dict[self.module_version_varname],
789 spec_dict[self.module_taglevel_varname])
791 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
793 def tag_name (self, spec_dict, old_svn_name=False):
794 base_tag_name = self.name
796 base_tag_name = git_to_svn_name(self.name)
797 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
800 ##############################
801 # using fine_grain means replacing only those instances that currently refer to this tag
802 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
803 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
804 newtagsfile=tagsfile+".new"
806 new=open(newtagsfile,"w")
809 # fine-grain : replace those lines that refer to oldname
811 if self.options.verbose:
812 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
813 matcher=re.compile("^(.*)%s(.*)"%oldname)
814 for line in tags.readlines():
815 if not matcher.match(line):
818 (begin,end)=matcher.match(line).groups()
819 new.write(begin+newname+end+"\n")
821 # brute-force : change uncommented lines that define <module>-SVNPATH
823 if self.options.verbose:
824 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
825 pattern="\A\s*(?P<make_name>[^\s]+)-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
827 matcher_module=re.compile(pattern)
828 for line in tags.readlines():
829 attempt=matcher_module.match(line)
831 if line.find("-GITPATH") >= 0:
832 modulepath = "%s-GITPATH"%(attempt.group('make_name'))
833 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
835 modulepath = "%s-SVNPATH"%(attempt.group('make_name'))
836 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
837 if self.options.verbose:
838 print ' ' + modulepath,
839 new.write(replacement)
845 os.rename(newtagsfile,tagsfile)
846 if self.options.verbose: print "%d changes"%matches
849 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
850 if self.options.verbose:
851 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
853 found_tagname = tagname
854 found = self.repository.tag_exists(tagname)
855 if not found and old_svn_tag_name:
856 if self.options.verbose:
858 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
859 found = self.repository.tag_exists(old_svn_tag_name)
861 found_tagname = old_svn_tag_name
863 if (found and need_it) or (not found and not need_it):
864 if self.options.verbose:
866 if found: print "- found"
867 else: print "- not found"
869 if self.options.verbose:
872 raise Exception, "tag (%s) is already there" % tagname
874 raise Exception, "can not find required tag (%s)" % tagname
879 ##############################
881 self.init_module_dir()
882 self.revert_module_dir()
883 self.update_module_dir()
885 spec_dict = self.spec_dict()
886 self.show_dict(spec_dict)
889 old_tag_name = self.tag_name(spec_dict)
890 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
892 if (self.options.new_version):
893 # new version set on command line
894 spec_dict[self.module_version_varname] = self.options.new_version
895 spec_dict[self.module_taglevel_varname] = 0
898 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
899 spec_dict[self.module_taglevel_varname] = new_taglevel
901 new_tag_name = self.tag_name(spec_dict)
904 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
905 new_tag_name = self.check_tag(new_tag_name, need_it=False)
908 diff_output = self.repository.diff_with_tag(old_tag_name)
909 if len(diff_output) == 0:
910 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
913 # side effect in trunk's specfile
914 self.patch_spec_var(spec_dict)
916 # prepare changelog file
917 # we use the standard subversion magic string (see svn_magic_line)
918 # so we can provide useful information, such as version numbers and diff
920 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
921 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
922 setting_tag_line=Module.setting_tag_format%new_tag_name
923 file(changelog,"w").write("""
926 Please write a changelog for this new tag in the section above
927 """%(Module.svn_magic_line,setting_tag_line))
929 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
930 file(changelog,"a").write('DIFF=========\n' + diff_output)
932 if self.options.debug:
936 self.run("%s %s"%(self.options.editor,changelog))
937 # strip magic line in second file - looks like svn has changed its magic line with 1.6
938 # so we do the job ourselves
939 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
940 # insert changelog in spec
941 if self.options.changelog:
942 self.insert_changelog (changelog,old_tag_name,new_tag_name)
945 build_path = os.path.join(self.options.workdir,
946 Module.config['build'])
947 build = Repository(build_path, self.options)
948 if self.options.build_branch:
949 build.to_branch(self.options.build_branch)
950 if not build.is_clean():
953 tagsfiles=glob(build.path+"/*-tags*.mk")
954 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
958 for tagsfile in tagsfiles:
959 status=tagsdict[tagsfile]
960 basename=os.path.basename(tagsfile)
961 print ".................... Dealing with %s"%basename
962 while tagsdict[tagsfile] == 'todo' :
963 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
964 [ ('y','es'), ('n', 'ext'), ('f','orce'),
965 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
968 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
970 print 'Done with %s'%os.path.basename(tagsfile)
971 tagsdict[tagsfile]='done'
973 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
975 print build.diff(f=tagsfile)
977 build.revert(f=tagsfile)
979 self.run("cat %s"%tagsfile)
982 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
983 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
984 d: show current diff for this tag file
985 r: revert that tag file
986 c: cat the current tag file
987 n: move to next file"""%locals()
989 if prompt("Want to review changes on tags files",False):
990 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
995 def diff_all_changes():
997 print self.repository.diff()
999 def commit_all_changes(log):
1000 self.repository.commit(log)
1003 self.run_prompt("Review module and build", diff_all_changes)
1004 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1005 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1007 if self.options.debug:
1008 print 'Preserving',changelog,'and stripped',changelog_svn
1010 os.unlink(changelog)
1011 os.unlink(changelog_svn)
1014 ##############################
1015 def do_version (self):
1016 self.init_module_dir()
1017 self.revert_module_dir()
1018 self.update_module_dir()
1019 spec_dict = self.spec_dict()
1020 if self.options.www:
1021 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1022 self.last_tag(spec_dict)))
1023 for varname in self.varnames:
1024 if not spec_dict.has_key(varname):
1025 self.html_print ('Could not find %%define for %s'%varname)
1028 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1029 if self.options.verbose:
1030 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1031 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1032 self.html_print_end()
1035 ##############################
1037 self.init_module_dir()
1038 self.revert_module_dir()
1039 self.update_module_dir()
1040 spec_dict = self.spec_dict()
1041 self.show_dict(spec_dict)
1044 tag_name = self.tag_name(spec_dict)
1045 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1048 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1050 if self.options.verbose:
1051 print 'Getting diff'
1052 diff_output = self.repository.diff_with_tag(tag_name)
1054 if self.options.list:
1058 thename=self.friendly_name()
1060 if self.options.www and diff_output:
1061 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1062 thename,self.last_tag(spec_dict),len(diff_output)))
1064 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1065 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1066 self.html_store_pre (diff_output)
1067 elif not self.options.www:
1068 print 'x'*30,'module',thename
1069 print 'x'*20,'<',tag_name
1070 print 'x'*20,'>',thename
1073 ##############################
1074 # store and restitute html fragments
1076 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1079 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1082 def html_quote (text):
1083 return text.replace('&','&').replace('<','<').replace('>','>')
1085 # only the fake error module has multiple titles
1086 def html_store_title (self, title):
1087 if not hasattr(self,'titles'): self.titles=[]
1088 self.titles.append(title)
1090 def html_store_raw (self, html):
1091 if not hasattr(self,'body'): self.body=''
1094 def html_store_pre (self, text):
1095 if not hasattr(self,'body'): self.body=''
1096 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1098 def html_print (self, txt):
1099 if not self.options.www:
1102 if not hasattr(self,'in_list') or not self.in_list:
1103 self.html_store_raw('<ul>')
1105 self.html_store_raw('<li>'+txt+'</li>')
1107 def html_print_end (self):
1108 if self.options.www:
1109 self.html_store_raw ('</ul>')
1112 def html_dump_header(title):
1113 nowdate=time.strftime("%Y-%m-%d")
1114 nowtime=time.strftime("%H:%M (%Z)")
1115 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1116 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1119 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1120 <style type="text/css">
1121 body { font-family:georgia, serif; }
1122 h1 {font-size: large; }
1123 p.title {font-size: x-large; }
1124 span.error {text-weight:bold; color: red; }
1128 <p class='title'> %s - status on %s at %s</p>
1130 """%(title,title,nowdate,nowtime)
1133 def html_dump_middle():
1137 def html_dump_footer():
1138 print "</body></html"
1140 def html_dump_toc(self):
1141 if hasattr(self,'titles'):
1142 for title in self.titles:
1143 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1145 def html_dump_body(self):
1146 if hasattr(self,'titles'):
1147 for title in self.titles:
1148 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1149 if hasattr(self,'body'):
1151 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1154 ##############################
1157 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1159 module-tools : a set of tools to manage subversion tags and specfile
1160 requires the specfile to either
1161 * define *version* and *taglevel*
1163 * define redirection variables module_version_varname / module_taglevel_varname
1165 by default, the trunk of modules is taken into account
1166 in this case, just mention the module name as <module_desc>
1168 if you wish to work on a branch rather than on the trunk,
1169 you can use something like e.g. Mom:2.1 as <module_desc>
1171 release_usage="""Usage: %prog [options] tag1 .. tagn
1172 Extract release notes from the changes in specfiles between several build tags, latest first
1174 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1175 You can refer to a (build) branch by prepending a colon, like in
1176 release-changelog :4.2 4.2-rc25
1177 You can refer to the build trunk by just mentioning 'trunk', e.g.
1178 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1180 common_usage="""More help:
1181 see http://svn.planet-lab.org/wiki/ModuleTools"""
1184 'list' : "displays a list of available tags or branches",
1185 'version' : "check latest specfile and print out details",
1186 'diff' : "show difference between module (trunk or branch) and latest tag",
1187 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1188 create new tag and and monitor its adoption in build/*-tags*.mk""",
1189 'branch' : """create a branch for this module, from the latest tag on the trunk,
1190 and change trunk's version number to reflect the new branch name;
1191 you can specify the new branch name by using module:branch""",
1192 'sync' : """create a tag from the module
1193 this is a last resort option, mostly for repairs""",
1194 'changelog' : """extract changelog between build tags
1195 expected arguments are a list of tags""",
1198 silent_modes = ['list']
1199 release_modes = ['changelog']
1202 def optparse_list (option, opt, value, parser):
1204 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1206 setattr(parser.values,option.dest,value.split())
1211 for function in Main.modes.keys():
1212 if sys.argv[0].find(function) >= 0:
1216 print "Unsupported command",sys.argv[0]
1217 print "Supported commands:" + " ".join(Main.modes.keys())
1220 if mode not in Main.release_modes:
1221 usage = Main.module_usage
1222 usage += Main.common_usage
1223 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1225 usage = Main.release_usage
1226 usage += Main.common_usage
1228 parser=OptionParser(usage=usage)
1230 if mode == "tag" or mode == 'branch':
1231 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1232 help="set new version and reset taglevel to 0")
1234 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1235 help="do not update changelog section in specfile when tagging")
1236 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1237 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1238 if mode == "tag" or mode == "sync" :
1239 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1240 help="specify editor")
1242 if mode in ["diff","version"] :
1243 parser.add_option("-W","--www", action="store", dest="www", default=False,
1244 help="export diff in html format, e.g. -W trunk")
1247 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1248 help="just list modules that exhibit differences")
1250 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1251 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1252 help="run on all modules as found in %s"%default_modules_list)
1253 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1254 help="run on all modules found in specified file")
1255 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1256 help="dry run - shell commands are only displayed")
1257 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1258 default=[], nargs=1,type="string",
1259 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1260 -- can be set multiple times, or use quotes""")
1262 parser.add_option("-w","--workdir", action="store", dest="workdir",
1263 default="%s/%s"%(os.getenv("HOME"),"modules"),
1264 help="""name for dedicated working dir - defaults to ~/modules
1265 ** THIS MUST NOT ** be your usual working directory""")
1266 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1267 help="skip safety checks, such as svn updates -- use with care")
1269 # default verbosity depending on function - temp
1270 verbose_modes= ['tag', 'sync', 'branch']
1272 if mode not in verbose_modes:
1273 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1274 help="run in verbose mode")
1276 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1277 help="run in quiet (non-verbose) mode")
1278 (options, args) = parser.parse_args()
1280 if not hasattr(options,'dry_run'):
1281 options.dry_run=False
1282 if not hasattr(options,'www'):
1288 if options.all_modules:
1289 options.modules_list=default_modules_list
1290 if options.modules_list:
1291 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1295 Module.init_homedir(options)
1298 modules=[ Module(modname,options) for modname in args ]
1299 # hack: create a dummy Module to store errors/warnings
1300 error_module = Module('__errors__',options)
1302 for module in modules:
1303 if len(args)>1 and mode not in Main.silent_modes:
1305 print '========================================',module.friendly_name()
1306 # call the method called do_<mode>
1307 method=Module.__dict__["do_%s"%mode]
1312 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1313 (module.friendly_name(), str(e))
1314 error_module.html_store_title(title)
1317 traceback.print_exc()
1318 print 'Skipping module %s: '%modname,e
1322 modetitle="Changes to tag in %s"%options.www
1323 elif mode == "version":
1324 modetitle="Latest tags in %s"%options.www
1325 modules.append(error_module)
1326 error_module.html_dump_header(modetitle)
1327 for module in modules:
1328 module.html_dump_toc()
1329 Module.html_dump_middle()
1330 for module in modules:
1331 module.html_dump_body()
1332 Module.html_dump_footer()
1334 ####################
1335 if __name__ == "__main__" :
1338 except KeyboardInterrupt: