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",
21 "NodeManager": "nodemanager"
24 def svn_to_git_name(module):
25 if RENAMED_SVN_MODULES.has_key(module):
26 return RENAMED_SVN_MODULES[module]
29 def git_to_svn_name(module):
30 for key in RENAMED_SVN_MODULES:
31 if module == RENAMED_SVN_MODULES[key]:
36 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
37 def prompt (question,default=True,other_choices=[],allow_outside=False):
38 if not isinstance (other_choices,list):
39 other_choices = [ other_choices ]
40 chars = [ c for (c,rest) in other_choices ]
44 if default is True: choices.append('[y]')
45 else : choices.append('y')
47 if default is False: choices.append('[n]')
48 else : choices.append('n')
50 for (char,choice) in other_choices:
52 choices.append("["+char+"]"+choice)
54 choices.append("<"+char+">"+choice)
56 answer=raw_input(question + " " + "/".join(choices) + " ? ")
59 answer=answer[0].lower()
61 if 'y' in chars: return 'y'
64 if 'n' in chars: return 'n'
67 for (char,choice) in other_choices:
72 return prompt(question,default,other_choices)
78 editor = os.environ['EDITOR']
86 def print_fold (line):
87 while len(line) >= fold_length:
88 print line[:fold_length],'\\'
89 line=line[fold_length:]
93 def __init__ (self,command,options):
96 self.tmp="/tmp/command-%d"%os.getpid()
99 if self.options.dry_run:
100 print 'dry_run',self.command
102 if self.options.verbose and self.options.mode not in Main.silent_modes:
103 print '+',self.command
105 return os.system(self.command)
107 def run_silent (self):
108 if self.options.dry_run:
109 print 'dry_run',self.command
111 if self.options.verbose:
112 print '+',self.command,' .. ',
114 retcod=os.system(self.command + " &> " + self.tmp)
116 print "FAILED ! -- out+err below (command was %s)"%self.command
117 os.system("cat " + self.tmp)
118 print "FAILED ! -- end of quoted output"
119 elif self.options.verbose:
125 if self.run_silent() !=0:
126 raise Exception,"Command %s failed"%self.command
128 # returns stdout, like bash's $(mycommand)
129 def output_of (self,with_stderr=False):
130 if self.options.dry_run:
131 print 'dry_run',self.command
132 return 'dry_run output'
133 tmp="/tmp/status-%d"%os.getpid()
134 if self.options.debug:
135 print '+',self.command,' .. ',
144 result=file(tmp).read()
146 if self.options.debug:
154 def __init__(self, path, options):
156 self.options = options
159 return os.path.basename(self.path)
162 out = Command("svn info %s" % self.path, self.options).output_of()
163 for line in out.split('\n'):
164 if line.startswith("URL:"):
165 return line.split()[1].strip()
168 out = Command("svn info %s" % self.path, self.options).output_of()
169 for line in out.split('\n'):
170 if line.startswith("Repository Root:"):
171 root = line.split()[2].strip()
172 return "%s/%s" % (root, self.name())
175 def checkout(cls, remote, local, options, recursive=False):
177 svncommand = "svn co %s %s" % (remote, local)
179 svncommand = "svn co -N %s %s" % (remote, local)
180 Command("rm -rf %s" % local, options).run_silent()
181 Command(svncommand, options).run_fatal()
183 return SvnRepository(local, options)
186 def remote_exists(cls, remote):
187 return os.system("svn list %s &> /dev/null" % remote) == 0
189 def tag_exists(self, tagname):
190 url = "%s/tags/%s" % (self.repo_root(), tagname)
191 return SvnRepository.remote_exists(url)
193 def update(self, subdir="", recursive=True, branch=None):
194 path = os.path.join(self.path, subdir)
196 svncommand = "svn up %s" % path
198 svncommand = "svn up -N %s" % path
199 Command(svncommand, self.options).run_fatal()
201 def commit(self, logfile):
202 # add all new files to the repository
203 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
204 self.path, self.options).output_of()
205 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
207 def to_branch(self, branch):
208 remote = "%s/branches/%s" % (self.repo_root(), branch)
209 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
211 def to_tag(self, tag):
212 remote = "%s/tags/%s" % (self.repo_root(), branch)
213 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
215 def tag(self, tagname, logfile):
216 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
217 self_url = self.url()
218 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
220 def diff(self, f=""):
222 f = os.path.join(self.path, f)
225 return Command("svn diff %s" % f, self.options).output_of(True)
227 def diff_with_tag(self, tagname):
228 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
229 return Command("svn diff %s %s" % (tag_url, self.url()),
230 self.options).output_of(True)
232 def revert(self, f=""):
234 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
237 Command("svn revert %s -R" % self.path, self.options).run_fatal()
238 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
239 self.path, self.options).run_silent()
242 command="svn status %s" % self.path
243 return len(Command(command,self.options).output_of(True)) == 0
246 return os.path.exists(os.path.join(self.path, ".svn"))
252 def __init__(self, path, options):
254 self.options = options
257 return os.path.basename(self.path)
263 c = Command("git remote show origin", self.options)
264 out = self.__run_in_repo(c.output_of)
265 for line in out.split('\n'):
266 if line.strip().startswith("Fetch URL:"):
267 repo = line.split()[2]
270 def checkout(cls, remote, local, options, depth=1):
271 Command("rm -rf %s" % local, options).run_silent()
272 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
273 return GitRepository(local, options)
276 def remote_exists(cls, remote):
277 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
279 def tag_exists(self, tagname):
280 command = 'git tag -l | grep "^%s$"' % tagname
281 c = Command(command, self.options)
282 out = self.__run_in_repo(c.output_of, with_stderr=True)
285 def __run_in_repo(self, fun, *args, **kwargs):
288 ret = fun(*args, **kwargs)
292 def __run_command_in_repo(self, command, ignore_errors=False):
293 c = Command(command, self.options)
295 return self.__run_in_repo(c.output_of)
297 return self.__run_in_repo(c.run_fatal)
299 def update(self, subdir=None, recursive=None, branch="master"):
300 if branch == "master":
301 self.__run_command_in_repo("git checkout %s" % branch)
303 self.__run_command_in_repo("git checkout origin/%s" % branch)
304 self.__run_command_in_repo("git fetch origin --tags")
305 self.__run_command_in_repo("git fetch origin")
306 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
308 def to_branch(self, branch, remote=True):
310 branch = "origin/%s" % branch
311 return self.__run_command_in_repo("git checkout %s" % branch)
313 def to_tag(self, tag):
314 return self.__run_command_in_repo("git checkout %s" % tag)
316 def tag(self, tagname, logfile):
317 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
320 def diff(self, f=""):
321 c = Command("git diff %s" % f, self.options)
322 return self.__run_in_repo(c.output_of, with_stderr=True)
324 def diff_with_tag(self, tagname):
325 c = Command("git diff %s" % tagname, self.options)
326 return self.__run_in_repo(c.output_of, with_stderr=True)
328 def commit(self, logfile):
329 self.__run_command_in_repo("git add .", ignore_errors=True)
330 self.__run_command_in_repo("git add -u", ignore_errors=True)
331 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
332 self.__run_command_in_repo("git push")
333 self.__run_command_in_repo("git push --tags")
335 def revert(self, f=""):
337 self.__run_command_in_repo("git checkout %s" % f)
340 self.__run_command_in_repo("git --no-pager reset --hard")
341 self.__run_command_in_repo("git --no-pager clean -f")
346 s="nothing to commit (working directory clean)"
347 return Command(command, self.options).output_of(True).find(s) >= 0
348 return self.__run_in_repo(check_commit)
351 return os.path.exists(os.path.join(self.path, ".git"))
355 """ Generic repository """
356 supported_repo_types = [SvnRepository, GitRepository]
358 def __init__(self, path, options):
360 self.options = options
361 for repo in self.supported_repo_types:
362 self.repo = repo(self.path, self.options)
363 if self.repo.is_valid():
367 def has_moved_to_git(cls, module, config):
368 module = git_to_svn_name(module)
369 # check if the module is already in Git
370 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
371 return GitRepository.remote_exists(Module.git_remote_dir(module))
375 def remote_exists(cls, remote):
376 for repo in Repository.supported_repo_types:
377 if repo.remote_exists(remote):
381 def __getattr__(self, attr):
382 return getattr(self.repo, attr)
386 # support for tagged module is minimal, and is for the Build class only
389 svn_magic_line="--This line, and those below, will be ignored--"
390 setting_tag_format = "Setting tag %s"
392 redirectors=[ # ('module_name_varname','name'),
393 ('module_version_varname','version'),
394 ('module_taglevel_varname','taglevel'), ]
396 # where to store user's config
397 config_storage="CONFIG"
402 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
403 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
404 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
405 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
406 ("build", "Enter the name of your build module","build"),
407 ('username',"Enter your firstname and lastname for changelogs",""),
408 ("email","Enter your email address for changelogs",""),
412 def prompt_config_option(cls, key, message, default):
413 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
416 def prompt_config (cls):
417 for (key,message,default) in cls.configKeys:
419 while not cls.config[key]:
420 cls.prompt_config_option(key, message, default)
423 # for parsing module spec name:branch
424 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
425 # special form for tagged module - for Build
426 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
428 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
430 def __init__ (self,module_spec,options):
432 attempt=Module.matcher_branch_spec.match(module_spec)
434 self.name=attempt.group('name')
435 self.branch=attempt.group('branch')
437 attempt=Module.matcher_tag_spec.match(module_spec)
439 self.name=attempt.group('name')
440 self.tagname=attempt.group('tagname')
442 self.name=module_spec
444 # when available prefer to use git module name internally
445 self.name = svn_to_git_name(self.name)
448 self.module_dir="%s/%s"%(options.workdir,self.name)
449 self.repository = None
452 def run (self,command):
453 return Command(command,self.options).run()
454 def run_fatal (self,command):
455 return Command(command,self.options).run_fatal()
456 def run_prompt (self,message,fun, *args):
457 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
458 if not self.options.verbose:
460 choice=prompt(message,True,('s','how'))
464 elif choice is False:
465 print 'About to run function:', fun_msg
467 question=message+" - want to run function: " + fun_msg
468 if prompt(question,True):
471 def friendly_name (self):
472 if hasattr(self,'branch'):
473 return "%s:%s"%(self.name,self.branch)
474 elif hasattr(self,'tagname'):
475 return "%s@%s"%(self.name,self.tagname)
480 def git_remote_dir (cls, name):
481 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
484 def svn_remote_dir (cls, name):
485 name = git_to_svn_name(name)
486 svn = cls.config['svnpath']
487 if svn.endswith('/'):
488 return "%s%s" % (svn, name)
489 return "%s/%s" % (svn, name)
491 def svn_selected_remote(self):
492 svn_name = git_to_svn_name(self.name)
493 remote = self.svn_remote_dir(svn_name)
494 if hasattr(self,'branch'):
495 remote = "%s/branches/%s" % (remote, self.branch)
496 elif hasattr(self,'tagname'):
497 remote = "%s/tags/%s" % (remote, self.tagname)
499 remote = "%s/trunk" % remote
504 def init_homedir (cls, options):
505 if options.verbose and options.mode not in Main.silent_modes:
506 print 'Checking for', options.workdir
507 storage="%s/%s"%(options.workdir, cls.config_storage)
508 # sanity check. Either the topdir exists AND we have a config/storage
509 # or topdir does not exist and we create it
510 # to avoid people use their own daily svn repo
511 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
512 print """The directory %s exists and has no CONFIG file
513 If this is your regular working directory, please provide another one as the
514 module-* commands need a fresh working dir. Make sure that you do not use
515 that for other purposes than tagging""" % options.workdir
518 def checkout_build():
519 print "Checking out build module..."
520 remote = cls.git_remote_dir(cls.config['build'])
521 local = os.path.join(options.workdir, cls.config['build'])
522 GitRepository.checkout(remote, local, options, depth=1)
527 for (key,message,default) in Module.configKeys:
528 f.write("%s=%s\n"%(key,Module.config[key]))
531 print 'Stored',storage
532 Command("cat %s"%storage,options).run()
537 for line in f.readlines():
538 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
539 Module.config[key]=value
542 if not os.path.isdir (options.workdir):
543 print "Cannot find",options.workdir,"let's create it"
544 Command("mkdir -p %s" % options.workdir, options).run_silent()
550 # check missing config options
552 for (key,message,default) in cls.configKeys:
553 if not Module.config.has_key(key):
554 print "Configuration changed for module-tools"
555 cls.prompt_config_option(key, message, default)
559 Command("rm -rf %s" % options.workdir, options).run_silent()
560 Command("mkdir -p %s" % options.workdir, options).run_silent()
564 build_dir = os.path.join(options.workdir, cls.config['build'])
565 if not os.path.isdir(build_dir):
568 build = Repository(build_dir, options)
569 if not build.is_clean():
570 print "build module needs a revert"
575 if options.verbose and options.mode not in Main.silent_modes:
576 print '******** Using config'
577 for (key,message,default) in Module.configKeys:
578 print '\t',key,'=',Module.config[key]
580 def init_module_dir (self):
581 if self.options.verbose:
582 print 'Checking for',self.module_dir
584 if not os.path.isdir (self.module_dir):
585 if Repository.has_moved_to_git(self.name, Module.config):
586 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
590 remote = self.svn_selected_remote()
591 self.repository = SvnRepository.checkout(remote,
593 self.options, recursive=False)
595 self.repository = Repository(self.module_dir, self.options)
596 if self.repository.type == "svn":
597 # check if module has moved to git
598 if Repository.has_moved_to_git(self.name, Module.config):
599 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
600 self.init_module_dir()
601 # check if we have the required branch/tag
602 if self.repository.url() != self.svn_selected_remote():
603 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
604 self.init_module_dir()
606 elif self.repository.type == "git":
607 if hasattr(self,'branch'):
608 self.repository.to_branch(self.branch)
609 elif hasattr(self,'tagname'):
610 self.repository.to_tag(self.tagname)
613 raise Exception, 'Cannot find %s - check module name'%self.module_dir
616 def revert_module_dir (self):
617 if self.options.fast_checks:
618 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
620 if self.options.verbose:
621 print 'Checking whether', self.module_dir, 'needs being reverted'
623 if not self.repository.is_clean():
624 self.repository.revert()
626 def update_module_dir (self):
627 if self.options.fast_checks:
628 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
630 if self.options.verbose:
631 print 'Updating', self.module_dir
633 if hasattr(self,'branch'):
634 self.repository.update(branch=self.branch)
635 elif hasattr(self,'tagname'):
636 self.repository.update(branch=self.tagname)
638 self.repository.update()
640 def main_specname (self):
641 attempt="%s/%s.spec"%(self.module_dir,self.name)
642 if os.path.isfile (attempt):
644 pattern1="%s/*.spec"%self.module_dir
645 level1=glob(pattern1)
648 pattern2="%s/*/*.spec"%self.module_dir
649 level2=glob(pattern2)
653 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
655 def all_specnames (self):
656 level1=glob("%s/*.spec" % self.module_dir)
657 if level1: return level1
658 level2=glob("%s/*/*.spec" % self.module_dir)
661 def parse_spec (self, specfile, varnames):
662 if self.options.verbose:
663 print 'Parsing',specfile,
669 for line in f.readlines():
670 attempt=Module.matcher_rpm_define.match(line)
672 (define,var,value)=attempt.groups()
676 if self.options.debug:
677 print 'found',len(result),'keys'
678 for (k,v) in result.iteritems():
682 # stores in self.module_name_varname the rpm variable to be used for the module's name
683 # and the list of these names in self.varnames
684 def spec_dict (self):
685 specfile=self.main_specname()
686 redirector_keys = [ varname for (varname,default) in Module.redirectors]
687 redirect_dict = self.parse_spec(specfile,redirector_keys)
688 if self.options.debug:
689 print '1st pass parsing done, redirect_dict=',redirect_dict
691 for (varname,default) in Module.redirectors:
692 if redirect_dict.has_key(varname):
693 setattr(self,varname,redirect_dict[varname])
694 varnames += [redirect_dict[varname]]
696 setattr(self,varname,default)
697 varnames += [ default ]
698 self.varnames = varnames
699 result = self.parse_spec (specfile,self.varnames)
700 if self.options.debug:
701 print '2st pass parsing done, varnames=',varnames,'result=',result
704 def patch_spec_var (self, patch_dict,define_missing=False):
705 for specfile in self.all_specnames():
706 # record the keys that were changed
707 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
708 newspecfile=specfile+".new"
709 if self.options.verbose:
710 print 'Patching',specfile,'for',patch_dict.keys()
712 new=open(newspecfile,"w")
714 for line in spec.readlines():
715 attempt=Module.matcher_rpm_define.match(line)
717 (define,var,value)=attempt.groups()
718 if var in patch_dict.keys():
719 if self.options.debug:
720 print 'rewriting %s as %s'%(var,patch_dict[var])
721 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
726 for (key,was_changed) in changed.iteritems():
728 if self.options.debug:
729 print 'rewriting missing %s as %s'%(key,patch_dict[key])
730 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
733 os.rename(newspecfile,specfile)
735 # returns all lines until the magic line
736 def unignored_lines (self, logfile):
738 white_line_matcher = re.compile("\A\s*\Z")
739 for logline in file(logfile).readlines():
740 if logline.strip() == Module.svn_magic_line:
742 elif white_line_matcher.match(logline):
745 result.append(logline.strip()+'\n')
748 # creates a copy of the input with only the unignored lines
749 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
751 f.write(self.setting_tag_format%new_tag_name + '\n')
752 for line in self.unignored_lines(filein):
756 def insert_changelog (self, logfile, oldtag, newtag):
757 for specfile in self.all_specnames():
758 newspecfile=specfile+".new"
759 if self.options.verbose:
760 print 'Inserting changelog from %s into %s'%(logfile,specfile)
762 new=open(newspecfile,"w")
763 for line in spec.readlines():
765 if re.compile('%changelog').match(line):
766 dateformat="* %a %b %d %Y"
767 datepart=time.strftime(dateformat)
768 logpart="%s <%s> - %s"%(Module.config['username'],
769 Module.config['email'],
771 new.write(datepart+" "+logpart+"\n")
772 for logline in self.unignored_lines(logfile):
773 new.write("- " + logline)
777 os.rename(newspecfile,specfile)
779 def show_dict (self, spec_dict):
780 if self.options.verbose:
781 for (k,v) in spec_dict.iteritems():
784 def last_tag (self, spec_dict):
786 return "%s-%s" % (spec_dict[self.module_version_varname],
787 spec_dict[self.module_taglevel_varname])
789 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
791 def tag_name (self, spec_dict, old_svn_name=False):
792 base_tag_name = self.name
794 base_tag_name = git_to_svn_name(self.name)
795 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
798 ##############################
799 # using fine_grain means replacing only those instances that currently refer to this tag
800 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
801 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
802 newtagsfile=tagsfile+".new"
804 new=open(newtagsfile,"w")
807 # fine-grain : replace those lines that refer to oldname
809 if self.options.verbose:
810 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
811 matcher=re.compile("^(.*)%s(.*)"%oldname)
812 for line in tags.readlines():
813 if not matcher.match(line):
816 (begin,end)=matcher.match(line).groups()
817 new.write(begin+newname+end+"\n")
819 # brute-force : change uncommented lines that define <module>-SVNPATH
821 if self.options.verbose:
822 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
823 pattern="\A\s*(?P<make_name>[^\s]+)-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
825 matcher_module=re.compile(pattern)
826 for line in tags.readlines():
827 attempt=matcher_module.match(line)
829 if line.find("-GITPATH") >= 0:
830 modulepath = "%s-GITPATH"%(attempt.group('make_name'))
831 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
833 modulepath = "%s-SVNPATH"%(attempt.group('make_name'))
834 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
835 if self.options.verbose:
836 print ' ' + modulepath,
837 new.write(replacement)
843 os.rename(newtagsfile,tagsfile)
844 if self.options.verbose: print "%d changes"%matches
847 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
848 if self.options.verbose:
849 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
851 found_tagname = tagname
852 found = self.repository.tag_exists(tagname)
853 if not found and old_svn_tag_name:
854 if self.options.verbose:
856 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
857 found = self.repository.tag_exists(old_svn_tag_name)
859 found_tagname = old_svn_tag_name
861 if (found and need_it) or (not found and not need_it):
862 if self.options.verbose:
864 if found: print "- found"
865 else: print "- not found"
867 if self.options.verbose:
870 raise Exception, "tag (%s) is already there" % tagname
872 raise Exception, "can not find required tag (%s)" % tagname
877 ##############################
879 self.init_module_dir()
880 self.revert_module_dir()
881 self.update_module_dir()
883 spec_dict = self.spec_dict()
884 self.show_dict(spec_dict)
887 old_tag_name = self.tag_name(spec_dict)
888 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
890 if (self.options.new_version):
891 # new version set on command line
892 spec_dict[self.module_version_varname] = self.options.new_version
893 spec_dict[self.module_taglevel_varname] = 0
896 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
897 spec_dict[self.module_taglevel_varname] = new_taglevel
899 new_tag_name = self.tag_name(spec_dict)
902 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
903 new_tag_name = self.check_tag(new_tag_name, need_it=False)
906 diff_output = self.repository.diff_with_tag(old_tag_name)
907 if len(diff_output) == 0:
908 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
911 # side effect in trunk's specfile
912 self.patch_spec_var(spec_dict)
914 # prepare changelog file
915 # we use the standard subversion magic string (see svn_magic_line)
916 # so we can provide useful information, such as version numbers and diff
918 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
919 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
920 setting_tag_line=Module.setting_tag_format%new_tag_name
921 file(changelog,"w").write("""
924 Please write a changelog for this new tag in the section above
925 """%(Module.svn_magic_line,setting_tag_line))
927 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
928 file(changelog,"a").write('DIFF=========\n' + diff_output)
930 if self.options.debug:
934 self.run("%s %s"%(self.options.editor,changelog))
935 # strip magic line in second file - looks like svn has changed its magic line with 1.6
936 # so we do the job ourselves
937 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
938 # insert changelog in spec
939 if self.options.changelog:
940 self.insert_changelog (changelog,old_tag_name,new_tag_name)
943 build_path = os.path.join(self.options.workdir,
944 Module.config['build'])
945 build = Repository(build_path, self.options)
946 if self.options.build_branch:
947 build.to_branch(self.options.build_branch)
948 if not build.is_clean():
951 tagsfiles=glob(build.path+"/*-tags*.mk")
952 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
956 for tagsfile in tagsfiles:
957 status=tagsdict[tagsfile]
958 basename=os.path.basename(tagsfile)
959 print ".................... Dealing with %s"%basename
960 while tagsdict[tagsfile] == 'todo' :
961 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
962 [ ('y','es'), ('n', 'ext'), ('f','orce'),
963 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
966 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
968 print 'Done with %s'%os.path.basename(tagsfile)
969 tagsdict[tagsfile]='done'
971 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
973 print build.diff(f=tagsfile)
975 build.revert(f=tagsfile)
977 self.run("cat %s"%tagsfile)
980 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
981 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
982 d: show current diff for this tag file
983 r: revert that tag file
984 c: cat the current tag file
985 n: move to next file"""%locals()
987 if prompt("Want to review changes on tags files",False):
988 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
993 def diff_all_changes():
995 print self.repository.diff()
997 def commit_all_changes(log):
998 self.repository.commit(log)
1001 self.run_prompt("Review module and build", diff_all_changes)
1002 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1003 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1005 if self.options.debug:
1006 print 'Preserving',changelog,'and stripped',changelog_svn
1008 os.unlink(changelog)
1009 os.unlink(changelog_svn)
1012 ##############################
1013 def do_version (self):
1014 self.init_module_dir()
1015 self.revert_module_dir()
1016 self.update_module_dir()
1017 spec_dict = self.spec_dict()
1018 if self.options.www:
1019 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1020 self.last_tag(spec_dict)))
1021 for varname in self.varnames:
1022 if not spec_dict.has_key(varname):
1023 self.html_print ('Could not find %%define for %s'%varname)
1026 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1027 if self.options.verbose:
1028 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1029 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1030 self.html_print_end()
1033 ##############################
1035 self.init_module_dir()
1036 self.revert_module_dir()
1037 self.update_module_dir()
1038 spec_dict = self.spec_dict()
1039 self.show_dict(spec_dict)
1042 tag_name = self.tag_name(spec_dict)
1043 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1046 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1048 if self.options.verbose:
1049 print 'Getting diff'
1050 diff_output = self.repository.diff_with_tag(tag_name)
1052 if self.options.list:
1056 thename=self.friendly_name()
1058 if self.options.www and diff_output:
1059 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1060 thename,self.last_tag(spec_dict),len(diff_output)))
1062 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1063 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1064 self.html_store_pre (diff_output)
1065 elif not self.options.www:
1066 print 'x'*30,'module',thename
1067 print 'x'*20,'<',tag_name
1068 print 'x'*20,'>',thename
1071 ##############################
1072 # store and restitute html fragments
1074 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1077 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1080 def html_quote (text):
1081 return text.replace('&','&').replace('<','<').replace('>','>')
1083 # only the fake error module has multiple titles
1084 def html_store_title (self, title):
1085 if not hasattr(self,'titles'): self.titles=[]
1086 self.titles.append(title)
1088 def html_store_raw (self, html):
1089 if not hasattr(self,'body'): self.body=''
1092 def html_store_pre (self, text):
1093 if not hasattr(self,'body'): self.body=''
1094 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1096 def html_print (self, txt):
1097 if not self.options.www:
1100 if not hasattr(self,'in_list') or not self.in_list:
1101 self.html_store_raw('<ul>')
1103 self.html_store_raw('<li>'+txt+'</li>')
1105 def html_print_end (self):
1106 if self.options.www:
1107 self.html_store_raw ('</ul>')
1110 def html_dump_header(title):
1111 nowdate=time.strftime("%Y-%m-%d")
1112 nowtime=time.strftime("%H:%M (%Z)")
1113 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1114 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1117 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1118 <style type="text/css">
1119 body { font-family:georgia, serif; }
1120 h1 {font-size: large; }
1121 p.title {font-size: x-large; }
1122 span.error {text-weight:bold; color: red; }
1126 <p class='title'> %s - status on %s at %s</p>
1128 """%(title,title,nowdate,nowtime)
1131 def html_dump_middle():
1135 def html_dump_footer():
1136 print "</body></html"
1138 def html_dump_toc(self):
1139 if hasattr(self,'titles'):
1140 for title in self.titles:
1141 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1143 def html_dump_body(self):
1144 if hasattr(self,'titles'):
1145 for title in self.titles:
1146 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1147 if hasattr(self,'body'):
1149 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1152 ##############################
1155 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1157 module-tools : a set of tools to manage subversion tags and specfile
1158 requires the specfile to either
1159 * define *version* and *taglevel*
1161 * define redirection variables module_version_varname / module_taglevel_varname
1163 by default, the trunk of modules is taken into account
1164 in this case, just mention the module name as <module_desc>
1166 if you wish to work on a branch rather than on the trunk,
1167 you can use something like e.g. Mom:2.1 as <module_desc>
1169 release_usage="""Usage: %prog [options] tag1 .. tagn
1170 Extract release notes from the changes in specfiles between several build tags, latest first
1172 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1173 You can refer to a (build) branch by prepending a colon, like in
1174 release-changelog :4.2 4.2-rc25
1175 You can refer to the build trunk by just mentioning 'trunk', e.g.
1176 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1178 common_usage="""More help:
1179 see http://svn.planet-lab.org/wiki/ModuleTools"""
1182 'list' : "displays a list of available tags or branches",
1183 'version' : "check latest specfile and print out details",
1184 'diff' : "show difference between module (trunk or branch) and latest tag",
1185 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1186 create new tag and and monitor its adoption in build/*-tags*.mk""",
1187 'branch' : """create a branch for this module, from the latest tag on the trunk,
1188 and change trunk's version number to reflect the new branch name;
1189 you can specify the new branch name by using module:branch""",
1190 'sync' : """create a tag from the module
1191 this is a last resort option, mostly for repairs""",
1192 'changelog' : """extract changelog between build tags
1193 expected arguments are a list of tags""",
1196 silent_modes = ['list']
1197 release_modes = ['changelog']
1200 def optparse_list (option, opt, value, parser):
1202 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1204 setattr(parser.values,option.dest,value.split())
1209 for function in Main.modes.keys():
1210 if sys.argv[0].find(function) >= 0:
1214 print "Unsupported command",sys.argv[0]
1215 print "Supported commands:" + " ".join(Main.modes.keys())
1218 if mode not in Main.release_modes:
1219 usage = Main.module_usage
1220 usage += Main.common_usage
1221 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1223 usage = Main.release_usage
1224 usage += Main.common_usage
1226 parser=OptionParser(usage=usage)
1228 if mode == "tag" or mode == 'branch':
1229 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1230 help="set new version and reset taglevel to 0")
1232 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1233 help="do not update changelog section in specfile when tagging")
1234 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1235 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1236 if mode == "tag" or mode == "sync" :
1237 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1238 help="specify editor")
1240 if mode in ["diff","version"] :
1241 parser.add_option("-W","--www", action="store", dest="www", default=False,
1242 help="export diff in html format, e.g. -W trunk")
1245 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1246 help="just list modules that exhibit differences")
1248 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1249 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1250 help="run on all modules as found in %s"%default_modules_list)
1251 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1252 help="run on all modules found in specified file")
1253 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1254 help="dry run - shell commands are only displayed")
1255 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1256 default=[], nargs=1,type="string",
1257 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1258 -- can be set multiple times, or use quotes""")
1260 parser.add_option("-w","--workdir", action="store", dest="workdir",
1261 default="%s/%s"%(os.getenv("HOME"),"modules"),
1262 help="""name for dedicated working dir - defaults to ~/modules
1263 ** THIS MUST NOT ** be your usual working directory""")
1264 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1265 help="skip safety checks, such as svn updates -- use with care")
1267 # default verbosity depending on function - temp
1268 verbose_modes= ['tag', 'sync', 'branch']
1270 if mode not in verbose_modes:
1271 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1272 help="run in verbose mode")
1274 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1275 help="run in quiet (non-verbose) mode")
1276 (options, args) = parser.parse_args()
1278 if not hasattr(options,'dry_run'):
1279 options.dry_run=False
1280 if not hasattr(options,'www'):
1286 if options.all_modules:
1287 options.modules_list=default_modules_list
1288 if options.modules_list:
1289 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1293 Module.init_homedir(options)
1296 modules=[ Module(modname,options) for modname in args ]
1297 # hack: create a dummy Module to store errors/warnings
1298 error_module = Module('__errors__',options)
1300 for module in modules:
1301 if len(args)>1 and mode not in Main.silent_modes:
1303 print '========================================',module.friendly_name()
1304 # call the method called do_<mode>
1305 method=Module.__dict__["do_%s"%mode]
1310 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1311 (module.friendly_name(), str(e))
1312 error_module.html_store_title(title)
1315 traceback.print_exc()
1316 print 'Skipping module %s: '%modname,e
1320 modetitle="Changes to tag in %s"%options.www
1321 elif mode == "version":
1322 modetitle="Latest tags in %s"%options.www
1323 modules.append(error_module)
1324 error_module.html_dump_header(modetitle)
1325 for module in modules:
1326 module.html_dump_toc()
1327 Module.html_dump_middle()
1328 for module in modules:
1329 module.html_dump_body()
1330 Module.html_dump_footer()
1332 ####################
1333 if __name__ == "__main__" :
1336 except KeyboardInterrupt: