3 import sys, os, os.path
8 from optparse import OptionParser
10 # HARDCODED NAME CHANGES
12 # Moving to git we decided to rename some of the repositories. Here is
13 # a map of name changes applied in git repositories.
14 RENAMED_SVN_MODULES = {
17 "BootManager": "bootmanager",
21 "NodeManager": "nodemanager",
22 "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 # for svn modules pathname is just the name of the module as
165 # all modules are at the root
169 out = Command("svn info %s" % self.path, self.options).output_of()
170 for line in out.split('\n'):
171 if line.startswith("URL:"):
172 return line.split()[1].strip()
175 out = Command("svn info %s" % self.path, self.options).output_of()
176 for line in out.split('\n'):
177 if line.startswith("Repository Root:"):
178 root = line.split()[2].strip()
179 return "%s/%s" % (root, self.pathname())
182 def checkout(cls, remote, local, options, recursive=False):
184 svncommand = "svn co %s %s" % (remote, local)
186 svncommand = "svn co -N %s %s" % (remote, local)
187 Command("rm -rf %s" % local, options).run_silent()
188 Command(svncommand, options).run_fatal()
190 return SvnRepository(local, options)
193 def remote_exists(cls, remote):
194 return os.system("svn list %s &> /dev/null" % remote) == 0
196 def tag_exists(self, tagname):
197 url = "%s/tags/%s" % (self.repo_root(), tagname)
198 return SvnRepository.remote_exists(url)
200 def update(self, subdir="", recursive=True, branch=None):
201 path = os.path.join(self.path, subdir)
203 svncommand = "svn up %s" % path
205 svncommand = "svn up -N %s" % path
206 Command(svncommand, self.options).run_fatal()
208 def commit(self, logfile):
209 # add all new files to the repository
210 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
211 self.path, self.options).output_of()
212 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
214 def to_branch(self, branch):
215 remote = "%s/branches/%s" % (self.repo_root(), branch)
216 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
218 def to_tag(self, tag):
219 remote = "%s/tags/%s" % (self.repo_root(), branch)
220 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
222 def tag(self, tagname, logfile):
223 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
224 self_url = self.url()
225 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
227 def diff(self, f=""):
229 f = os.path.join(self.path, f)
232 return Command("svn diff %s" % f, self.options).output_of(True)
234 def diff_with_tag(self, tagname):
235 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
236 return Command("svn diff %s %s" % (tag_url, self.url()),
237 self.options).output_of(True)
239 def revert(self, f=""):
241 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
244 Command("svn revert %s -R" % self.path, self.options).run_fatal()
245 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
246 self.path, self.options).run_silent()
249 command="svn status %s" % self.path
250 return len(Command(command,self.options).output_of(True)) == 0
253 return os.path.exists(os.path.join(self.path, ".svn"))
259 def __init__(self, path, options):
261 self.options = options
264 return os.path.basename(self.path)
267 return self.repo_root()
270 c = Command("git show | grep commit | awk '{print $2;}'", self.options)
271 out = self.__run_in_repo(c.output_of).strip()
272 return "http://git.onelab.eu/?p=%s.git;a=commit;h=%s" % (self.name(), out)
275 c = Command("git remote show origin", self.options)
276 out = self.__run_in_repo(c.output_of)
277 for line in out.split('\n'):
278 if line.strip().startswith("Fetch URL:"):
279 return line.split()[2]
282 def checkout(cls, remote, local, options, depth=0):
283 Command("rm -rf %s" % local, options).run_silent()
284 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
285 return GitRepository(local, options)
288 def remote_exists(cls, remote):
289 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
291 def tag_exists(self, tagname):
292 command = 'git tag -l | grep "^%s$"' % tagname
293 c = Command(command, self.options)
294 out = self.__run_in_repo(c.output_of, with_stderr=True)
297 def __run_in_repo(self, fun, *args, **kwargs):
300 ret = fun(*args, **kwargs)
304 def __run_command_in_repo(self, command, ignore_errors=False):
305 c = Command(command, self.options)
307 return self.__run_in_repo(c.output_of)
309 return self.__run_in_repo(c.run_fatal)
311 def __is_commit_id(self, id):
312 c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
313 ret = self.__run_in_repo(c.output_of, with_stderr=False)
314 if ret.strip() == id:
318 def update(self, subdir=None, recursive=None, branch="master"):
319 if branch == "master":
320 self.__run_command_in_repo("git checkout %s" % branch)
322 self.to_branch(branch, remote=True)
323 self.__run_command_in_repo("git fetch origin --tags")
324 self.__run_command_in_repo("git fetch origin")
325 if not self.__is_commit_id(branch):
326 # we don't need to merge anythign for commit ids.
327 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
329 def to_branch(self, branch, remote=True):
332 command = "git branch --track %s origin/%s" % (branch, branch)
333 c = Command(command, self.options)
334 self.__run_in_repo(c.output_of, with_stderr=True)
335 return self.__run_command_in_repo("git checkout %s" % branch)
337 def to_tag(self, tag):
339 return self.__run_command_in_repo("git checkout %s" % tag)
341 def tag(self, tagname, logfile):
342 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
345 def diff(self, f=""):
346 c = Command("git diff %s" % f, self.options)
347 return self.__run_in_repo(c.output_of, with_stderr=True)
349 def diff_with_tag(self, tagname):
350 c = Command("git diff %s" % tagname, self.options)
351 return self.__run_in_repo(c.output_of, with_stderr=True)
353 def commit(self, logfile, branch="master"):
354 self.__run_command_in_repo("git add .", ignore_errors=True)
355 self.__run_command_in_repo("git add -u", ignore_errors=True)
356 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
357 if branch == "master" or self.__is_commit_id(branch):
358 self.__run_command_in_repo("git push")
360 self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
361 self.__run_command_in_repo("git push --tags")
363 def revert(self, f=""):
365 self.__run_command_in_repo("git checkout %s" % f)
368 self.__run_command_in_repo("git --no-pager reset --hard")
369 self.__run_command_in_repo("git --no-pager clean -f")
374 s="nothing to commit (working directory clean)"
375 return Command(command, self.options).output_of(True).find(s) >= 0
376 return self.__run_in_repo(check_commit)
379 return os.path.exists(os.path.join(self.path, ".git"))
383 """ Generic repository """
384 supported_repo_types = [SvnRepository, GitRepository]
386 def __init__(self, path, options):
388 self.options = options
389 for repo in self.supported_repo_types:
390 self.repo = repo(self.path, self.options)
391 if self.repo.is_valid():
395 def has_moved_to_git(cls, module, config):
396 module = svn_to_git_name(module)
397 # check if the module is already in Git
398 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
399 return GitRepository.remote_exists(Module.git_remote_dir(module))
403 def remote_exists(cls, remote):
404 for repo in Repository.supported_repo_types:
405 if repo.remote_exists(remote):
409 def __getattr__(self, attr):
410 return getattr(self.repo, attr)
414 # support for tagged module is minimal, and is for the Build class only
417 svn_magic_line="--This line, and those below, will be ignored--"
418 setting_tag_format = "Setting tag %s"
420 redirectors=[ # ('module_name_varname','name'),
421 ('module_version_varname','version'),
422 ('module_taglevel_varname','taglevel'), ]
424 # where to store user's config
425 config_storage="CONFIG"
430 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
431 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
432 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
433 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
434 ("build", "Enter the name of your build module","build"),
435 ('username',"Enter your firstname and lastname for changelogs",""),
436 ("email","Enter your email address for changelogs",""),
440 def prompt_config_option(cls, key, message, default):
441 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
444 def prompt_config (cls):
445 for (key,message,default) in cls.configKeys:
447 while not cls.config[key]:
448 cls.prompt_config_option(key, message, default)
450 # for parsing module spec name:branch
451 matcher_branch_spec=re.compile("\A(?P<name>[\w\.\-\/]+):(?P<branch>[\w\.\-]+)\Z")
452 # special form for tagged module - for Build
453 matcher_tag_spec=re.compile("\A(?P<name>[\w\.\-\/]+)@(?P<tagname>[\w\.\-]+)\Z")
455 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
458 def parse_module_spec(cls, module_spec):
459 name = branch_or_tagname = module_type = ""
461 attempt=Module.matcher_branch_spec.match(module_spec)
463 module_type = "branch"
464 name=attempt.group('name')
465 branch_or_tagname=attempt.group('branch')
467 attempt=Module.matcher_tag_spec.match(module_spec)
470 name=attempt.group('name')
471 branch_or_tagname=attempt.group('tagname')
474 return name, branch_or_tagname, module_type
477 def __init__ (self,module_spec,options):
479 self.pathname, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
480 self.name = os.path.basename(self.pathname)
482 if module_type == "branch":
483 self.branch=branch_or_tagname
484 elif module_type == "tag":
485 self.tagname=branch_or_tagname
487 # when available prefer to use git module name internally
488 self.name = svn_to_git_name(self.name)
491 self.module_dir="%s/%s"%(options.workdir,self.pathname)
492 self.repository = None
495 def run (self,command):
496 return Command(command,self.options).run()
497 def run_fatal (self,command):
498 return Command(command,self.options).run_fatal()
499 def run_prompt (self,message,fun, *args):
500 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
501 if not self.options.verbose:
503 choice=prompt(message,True,('s','how'))
507 elif choice is False:
508 print 'About to run function:', fun_msg
510 question=message+" - want to run function: " + fun_msg
511 if prompt(question,True):
514 def friendly_name (self):
515 if hasattr(self,'branch'):
516 return "%s:%s"%(self.pathname,self.branch)
517 elif hasattr(self,'tagname'):
518 return "%s@%s"%(self.pathname,self.tagname)
523 def git_remote_dir (cls, name):
524 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
527 def svn_remote_dir (cls, name):
528 name = git_to_svn_name(name)
529 svn = cls.config['svnpath']
530 if svn.endswith('/'):
531 return "%s%s" % (svn, name)
532 return "%s/%s" % (svn, name)
534 def svn_selected_remote(self):
535 svn_name = git_to_svn_name(self.name)
536 remote = self.svn_remote_dir(svn_name)
537 if hasattr(self,'branch'):
538 remote = "%s/branches/%s" % (remote, self.branch)
539 elif hasattr(self,'tagname'):
540 remote = "%s/tags/%s" % (remote, self.tagname)
542 remote = "%s/trunk" % remote
547 def init_homedir (cls, options):
548 if options.verbose and options.mode not in Main.silent_modes:
549 print 'Checking for', options.workdir
550 storage="%s/%s"%(options.workdir, cls.config_storage)
551 # sanity check. Either the topdir exists AND we have a config/storage
552 # or topdir does not exist and we create it
553 # to avoid people use their own daily svn repo
554 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
555 print """The directory %s exists and has no CONFIG file
556 If this is your regular working directory, please provide another one as the
557 module-* commands need a fresh working dir. Make sure that you do not use
558 that for other purposes than tagging""" % options.workdir
561 def checkout_build():
562 print "Checking out build module..."
563 remote = cls.git_remote_dir(cls.config['build'])
564 local = os.path.join(options.workdir, cls.config['build'])
565 GitRepository.checkout(remote, local, options, depth=1)
570 for (key,message,default) in Module.configKeys:
571 f.write("%s=%s\n"%(key,Module.config[key]))
574 print 'Stored',storage
575 Command("cat %s"%storage,options).run()
580 for line in f.readlines():
581 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
582 Module.config[key]=value
585 # owerride config variables using options.
586 if options.build_module:
587 Module.config['build'] = options.build_module
589 if not os.path.isdir (options.workdir):
590 print "Cannot find",options.workdir,"let's create it"
591 Command("mkdir -p %s" % options.workdir, options).run_silent()
597 # check missing config options
599 for (key,message,default) in cls.configKeys:
600 if not Module.config.has_key(key):
601 print "Configuration changed for module-tools"
602 cls.prompt_config_option(key, message, default)
606 Command("rm -rf %s" % options.workdir, options).run_silent()
607 Command("mkdir -p %s" % options.workdir, options).run_silent()
611 build_dir = os.path.join(options.workdir, cls.config['build'])
612 if not os.path.isdir(build_dir):
615 build = Repository(build_dir, options)
616 if not build.is_clean():
617 print "build module needs a revert"
622 if options.verbose and options.mode not in Main.silent_modes:
623 print '******** Using config'
624 for (key,message,default) in Module.configKeys:
625 print '\t',key,'=',Module.config[key]
627 def init_module_dir (self):
628 if self.options.verbose:
629 print 'Checking for',self.module_dir
631 if not os.path.isdir (self.module_dir):
632 if Repository.has_moved_to_git(self.pathname, Module.config):
633 self.repository = GitRepository.checkout(self.git_remote_dir(self.pathname),
637 remote = self.svn_selected_remote()
638 self.repository = SvnRepository.checkout(remote,
640 self.options, recursive=False)
642 self.repository = Repository(self.module_dir, self.options)
643 if self.repository.type == "svn":
644 # check if module has moved to git
645 if Repository.has_moved_to_git(self.pathname, Module.config):
646 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
647 self.init_module_dir()
648 # check if we have the required branch/tag
649 if self.repository.url() != self.svn_selected_remote():
650 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
651 self.init_module_dir()
653 elif self.repository.type == "git":
654 if hasattr(self,'branch'):
655 self.repository.to_branch(self.branch)
656 elif hasattr(self,'tagname'):
657 self.repository.to_tag(self.tagname)
660 raise Exception, 'Cannot find %s - check module name'%self.module_dir
663 def revert_module_dir (self):
664 if self.options.fast_checks:
665 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
667 if self.options.verbose:
668 print 'Checking whether', self.module_dir, 'needs being reverted'
670 if not self.repository.is_clean():
671 self.repository.revert()
673 def update_module_dir (self):
674 if self.options.fast_checks:
675 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
677 if self.options.verbose:
678 print 'Updating', self.module_dir
680 if hasattr(self,'branch'):
681 self.repository.update(branch=self.branch)
682 elif hasattr(self,'tagname'):
683 self.repository.update(branch=self.tagname)
685 self.repository.update()
687 def main_specname (self):
688 attempt="%s/%s.spec"%(self.module_dir,self.name)
689 if os.path.isfile (attempt):
691 pattern1="%s/*.spec"%self.module_dir
692 level1=glob(pattern1)
695 pattern2="%s/*/*.spec"%self.module_dir
696 level2=glob(pattern2)
700 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.pathname,pattern1,pattern2)
702 def all_specnames (self):
703 level1=glob("%s/*.spec" % self.module_dir)
704 if level1: return level1
705 level2=glob("%s/*/*.spec" % self.module_dir)
708 def parse_spec (self, specfile, varnames):
709 if self.options.verbose:
710 print 'Parsing',specfile,
716 for line in f.readlines():
717 attempt=Module.matcher_rpm_define.match(line)
719 (define,var,value)=attempt.groups()
723 if self.options.debug:
724 print 'found',len(result),'keys'
725 for (k,v) in result.iteritems():
729 # stores in self.module_name_varname the rpm variable to be used for the module's name
730 # and the list of these names in self.varnames
731 def spec_dict (self):
732 specfile=self.main_specname()
733 redirector_keys = [ varname for (varname,default) in Module.redirectors]
734 redirect_dict = self.parse_spec(specfile,redirector_keys)
735 if self.options.debug:
736 print '1st pass parsing done, redirect_dict=',redirect_dict
738 for (varname,default) in Module.redirectors:
739 if redirect_dict.has_key(varname):
740 setattr(self,varname,redirect_dict[varname])
741 varnames += [redirect_dict[varname]]
743 setattr(self,varname,default)
744 varnames += [ default ]
745 self.varnames = varnames
746 result = self.parse_spec (specfile,self.varnames)
747 if self.options.debug:
748 print '2st pass parsing done, varnames=',varnames,'result=',result
751 def patch_spec_var (self, patch_dict,define_missing=False):
752 for specfile in self.all_specnames():
753 # record the keys that were changed
754 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
755 newspecfile=specfile+".new"
756 if self.options.verbose:
757 print 'Patching',specfile,'for',patch_dict.keys()
759 new=open(newspecfile,"w")
761 for line in spec.readlines():
762 attempt=Module.matcher_rpm_define.match(line)
764 (define,var,value)=attempt.groups()
765 if var in patch_dict.keys():
766 if self.options.debug:
767 print 'rewriting %s as %s'%(var,patch_dict[var])
768 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
773 for (key,was_changed) in changed.iteritems():
775 if self.options.debug:
776 print 'rewriting missing %s as %s'%(key,patch_dict[key])
777 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
780 os.rename(newspecfile,specfile)
782 # returns all lines until the magic line
783 def unignored_lines (self, logfile):
785 white_line_matcher = re.compile("\A\s*\Z")
786 for logline in file(logfile).readlines():
787 if logline.strip() == Module.svn_magic_line:
789 elif white_line_matcher.match(logline):
792 result.append(logline.strip()+'\n')
795 # creates a copy of the input with only the unignored lines
796 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
798 f.write(self.setting_tag_format%new_tag_name + '\n')
799 for line in self.unignored_lines(filein):
803 def insert_changelog (self, logfile, oldtag, newtag):
804 for specfile in self.all_specnames():
805 newspecfile=specfile+".new"
806 if self.options.verbose:
807 print 'Inserting changelog from %s into %s'%(logfile,specfile)
809 new=open(newspecfile,"w")
810 for line in spec.readlines():
812 if re.compile('%changelog').match(line):
813 dateformat="* %a %b %d %Y"
814 datepart=time.strftime(dateformat)
815 logpart="%s <%s> - %s"%(Module.config['username'],
816 Module.config['email'],
818 new.write(datepart+" "+logpart+"\n")
819 for logline in self.unignored_lines(logfile):
820 new.write("- " + logline)
824 os.rename(newspecfile,specfile)
826 def show_dict (self, spec_dict):
827 if self.options.verbose:
828 for (k,v) in spec_dict.iteritems():
831 def last_tag (self, spec_dict):
833 return "%s-%s" % (spec_dict[self.module_version_varname],
834 spec_dict[self.module_taglevel_varname])
836 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
838 def tag_name (self, spec_dict, old_svn_name=False):
839 base_tag_name = self.name
841 base_tag_name = git_to_svn_name(self.name)
842 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
845 ##############################
846 # using fine_grain means replacing only those instances that currently refer to this tag
847 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
848 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
849 newtagsfile=tagsfile+".new"
851 new=open(newtagsfile,"w")
854 # fine-grain : replace those lines that refer to oldname
856 if self.options.verbose:
857 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
858 matcher=re.compile("^(.*)%s(.*)"%oldname)
859 for line in tags.readlines():
860 if not matcher.match(line):
863 (begin,end)=matcher.match(line).groups()
864 new.write(begin+newname+end+"\n")
866 # brute-force : change uncommented lines that define <module>-SVNPATH
868 if self.options.verbose:
869 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.pathname,tagsfile),
870 pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
871 %(self.name,self.name)
872 matcher_module=re.compile(pattern)
873 for line in tags.readlines():
874 attempt=matcher_module.match(line)
876 if line.find("-GITPATH") >= 0:
877 modulepath = "%s-GITPATH"%self.name
878 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.pathname,newname)
880 modulepath = "%s-SVNPATH"%self.name
881 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
882 if self.options.verbose:
883 print ' ' + modulepath,
884 new.write(replacement)
890 os.rename(newtagsfile,tagsfile)
891 if self.options.verbose: print "%d changes"%matches
894 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
895 if self.options.verbose:
896 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
898 found_tagname = tagname
899 found = self.repository.tag_exists(tagname)
900 if not found and old_svn_tag_name:
901 if self.options.verbose:
903 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
904 found = self.repository.tag_exists(old_svn_tag_name)
906 found_tagname = old_svn_tag_name
908 if (found and need_it) or (not found and not need_it):
909 if self.options.verbose:
911 if found: print "- found"
912 else: print "- not found"
914 if self.options.verbose:
917 raise Exception, "tag (%s) is already there" % tagname
919 raise Exception, "can not find required tag (%s)" % tagname
924 ##############################
926 self.init_module_dir()
927 self.revert_module_dir()
928 self.update_module_dir()
930 spec_dict = self.spec_dict()
931 self.show_dict(spec_dict)
934 old_tag_name = self.tag_name(spec_dict)
935 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
937 if (self.options.new_version):
938 # new version set on command line
939 spec_dict[self.module_version_varname] = self.options.new_version
940 spec_dict[self.module_taglevel_varname] = 0
943 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
944 spec_dict[self.module_taglevel_varname] = new_taglevel
946 new_tag_name = self.tag_name(spec_dict)
949 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
950 new_tag_name = self.check_tag(new_tag_name, need_it=False)
953 diff_output = self.repository.diff_with_tag(old_tag_name)
954 if len(diff_output) == 0:
955 if not prompt ("No pending difference in module %s, want to tag anyway"%self.pathname,False):
958 # side effect in trunk's specfile
959 self.patch_spec_var(spec_dict)
961 # prepare changelog file
962 # we use the standard subversion magic string (see svn_magic_line)
963 # so we can provide useful information, such as version numbers and diff
965 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
966 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
967 setting_tag_line=Module.setting_tag_format%new_tag_name
968 file(changelog,"w").write("""
971 Please write a changelog for this new tag in the section above
972 """%(Module.svn_magic_line,setting_tag_line))
974 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
975 file(changelog,"a").write('DIFF=========\n' + diff_output)
977 if self.options.debug:
981 self.run("%s %s"%(self.options.editor,changelog))
982 # strip magic line in second file - looks like svn has changed its magic line with 1.6
983 # so we do the job ourselves
984 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
985 # insert changelog in spec
986 if self.options.changelog:
987 self.insert_changelog (changelog,old_tag_name,new_tag_name)
990 build_path = os.path.join(self.options.workdir,
991 Module.config['build'])
992 build = Repository(build_path, self.options)
993 if self.options.build_branch:
994 build.to_branch(self.options.build_branch)
995 if not build.is_clean():
998 tagsfiles=glob(build.path+"/*-tags.mk")
999 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
1000 default_answer = 'y'
1003 for tagsfile in tagsfiles:
1004 status=tagsdict[tagsfile]
1005 basename=os.path.basename(tagsfile)
1006 print ".................... Dealing with %s"%basename
1007 while tagsdict[tagsfile] == 'todo' :
1008 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
1009 [ ('y','es'), ('n', 'ext'), ('f','orce'),
1010 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
1013 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1015 print 'Done with %s'%os.path.basename(tagsfile)
1016 tagsdict[tagsfile]='done'
1018 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1020 print build.diff(f=os.path.basename(tagsfile))
1022 build.revert(f=tagsfile)
1024 self.run("cat %s"%tagsfile)
1027 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1028 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1029 d: show current diff for this tag file
1030 r: revert that tag file
1031 c: cat the current tag file
1032 n: move to next file"""%locals()
1034 if prompt("Want to review changes on tags files",False):
1035 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1040 def diff_all_changes():
1042 print self.repository.diff()
1044 def commit_all_changes(log):
1045 if hasattr(self,'branch'):
1046 self.repository.commit(log, branch=self.branch)
1048 self.repository.commit(log)
1051 self.run_prompt("Review module and build", diff_all_changes)
1052 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1053 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1055 if self.options.debug:
1056 print 'Preserving',changelog,'and stripped',changelog_svn
1058 os.unlink(changelog)
1059 os.unlink(changelog_svn)
1062 ##############################
1063 def do_version (self):
1064 self.init_module_dir()
1065 self.revert_module_dir()
1066 self.update_module_dir()
1067 spec_dict = self.spec_dict()
1068 if self.options.www:
1069 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1070 self.last_tag(spec_dict)))
1071 for varname in self.varnames:
1072 if not spec_dict.has_key(varname):
1073 self.html_print ('Could not find %%define for %s'%varname)
1076 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1077 self.html_print ("%-16s %s"%('url',self.repository.url()))
1078 if self.options.verbose:
1079 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1080 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1081 self.html_print_end()
1084 ##############################
1086 self.init_module_dir()
1087 self.revert_module_dir()
1088 self.update_module_dir()
1089 spec_dict = self.spec_dict()
1090 self.show_dict(spec_dict)
1093 tag_name = self.tag_name(spec_dict)
1094 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1097 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1099 if self.options.verbose:
1100 print 'Getting diff'
1101 diff_output = self.repository.diff_with_tag(tag_name)
1103 if self.options.list:
1107 thename=self.friendly_name()
1109 if self.options.www and diff_output:
1110 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1111 thename,self.last_tag(spec_dict),len(diff_output)))
1113 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1114 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1115 self.html_store_pre (diff_output)
1116 elif not self.options.www:
1117 print 'x'*30,'module',thename
1118 print 'x'*20,'<',tag_name
1119 print 'x'*20,'>',thename
1122 ##############################
1123 # store and restitute html fragments
1125 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1128 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1131 def html_quote (text):
1132 return text.replace('&','&').replace('<','<').replace('>','>')
1134 # only the fake error module has multiple titles
1135 def html_store_title (self, title):
1136 if not hasattr(self,'titles'): self.titles=[]
1137 self.titles.append(title)
1139 def html_store_raw (self, html):
1140 if not hasattr(self,'body'): self.body=''
1143 def html_store_pre (self, text):
1144 if not hasattr(self,'body'): self.body=''
1145 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1147 def html_print (self, txt):
1148 if not self.options.www:
1151 if not hasattr(self,'in_list') or not self.in_list:
1152 self.html_store_raw('<ul>')
1154 self.html_store_raw('<li>'+txt+'</li>')
1156 def html_print_end (self):
1157 if self.options.www:
1158 self.html_store_raw ('</ul>')
1161 def html_dump_header(title):
1162 nowdate=time.strftime("%Y-%m-%d")
1163 nowtime=time.strftime("%H:%M (%Z)")
1164 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1165 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1168 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1169 <style type="text/css">
1170 body { font-family:georgia, serif; }
1171 h1 {font-size: large; }
1172 p.title {font-size: x-large; }
1173 span.error {text-weight:bold; color: red; }
1177 <p class='title'> %s - status on %s at %s</p>
1179 """%(title,title,nowdate,nowtime)
1182 def html_dump_middle():
1186 def html_dump_footer():
1187 print "</body></html"
1189 def html_dump_toc(self):
1190 if hasattr(self,'titles'):
1191 for title in self.titles:
1192 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1194 def html_dump_body(self):
1195 if hasattr(self,'titles'):
1196 for title in self.titles:
1197 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1198 if hasattr(self,'body'):
1200 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1204 class Build(Module):
1206 def __get_modules(self, tagfile):
1207 self.init_module_dir()
1210 tagfile = os.path.join(self.module_dir, tagfile)
1211 for line in open(tagfile):
1213 name, url = line.split(':=')
1214 name, git_or_svn_path = name.rsplit('-', 1)
1215 name = svn_to_git_name(name.strip())
1216 modules[name] = (git_or_svn_path.strip(), url.strip())
1221 def get_modules(self, tagfile):
1222 modules = self.__get_modules(tagfile)
1223 for module in modules:
1224 module_type = tag_or_branch = ""
1226 path_type, url = modules[module]
1227 if path_type == "GITPATH":
1228 module_spec = os.path.split(url)[-1].replace(".git","")
1229 name, tag_or_branch, module_type = self.parse_module_spec(module_spec)
1231 tag_or_branch = os.path.split(url)[-1].strip()
1232 if url.find('/tags/') >= 0:
1234 elif url.find('/branches/') >= 0:
1235 module_type = "branch"
1237 modules[module] = {"module_type" : module_type,
1238 "path_type": path_type,
1239 "tag_or_branch": tag_or_branch,
1245 def modules_diff(first, second):
1248 for module in first:
1249 if module not in second:
1250 print "=== module %s missing in right-hand side ==="%module
1252 if first[module]['tag_or_branch'] != second[module]['tag_or_branch']:
1253 diff[module] = (first[module]['tag_or_branch'], second[module]['tag_or_branch'])
1255 first_set = set(first.keys())
1256 second_set = set(second.keys())
1258 new_modules = list(second_set - first_set)
1259 removed_modules = list(first_set - second_set)
1261 return diff, new_modules, removed_modules
1263 def release_changelog(options, buildtag_old, buildtag_new):
1266 tagfile = options.distrotags[0]
1267 if not tagfile: raise
1269 print "ERROR: provide a tagfile name (eg. onelab, onelab-k27, planetlab)"
1271 # mmh, sounds wrong to blindly add the extension
1272 # if in a build directory, guess from existing files
1273 if os.path.isfile (tagfile):
1275 elif os.path.isfile ("%s-tags.mk" % tagfile):
1276 tagfile="%s-tags.mk" % tagfile
1278 tagfile = "%s-tags.mk" % tagfile
1283 print '= build tag %s to %s =' % (buildtag_old, buildtag_new)
1284 print '== distro %s (%s to %s) ==' % (tagfile, buildtag_old, buildtag_new)
1286 build = Build("build@%s" % buildtag_old, options)
1287 build.init_module_dir()
1288 first = build.get_modules(tagfile)
1290 print ' * from', buildtag_old, build.repository.gitweb()
1292 build = Build("build@%s" % buildtag_new, options)
1293 build.init_module_dir()
1294 second = build.get_modules(tagfile)
1296 print ' * to', buildtag_new, build.repository.gitweb()
1298 diff, new_modules, removed_modules = modules_diff(first, second)
1301 def get_module(name, tag):
1302 if not tag or tag == "trunk":
1303 return Module("%s" % (module), options)
1305 return Module("%s@%s" % (module, tag), options)
1309 print '=== %s - %s to %s : package %s ===' % (tagfile, buildtag_old, buildtag_new, module)
1311 first, second = diff[module]
1312 m = get_module(module, first)
1313 os.system('rm -rf %s' % m.module_dir) # cleanup module dir
1316 if m.repository.type == "svn":
1317 print ' * from', first, m.repository.url()
1319 print ' * from', first, m.repository.gitweb()
1321 specfile = m.main_specname()
1322 (tmpfd, tmpfile) = tempfile.mkstemp()
1323 os.system("cp -f /%s %s" % (specfile, tmpfile))
1325 m = get_module(module, second)
1327 specfile = m.main_specname()
1329 if m.repository.type == "svn":
1330 print ' * to', second, m.repository.url()
1332 print ' * to', second, m.repository.gitweb()
1335 os.system("diff -u %s %s | sed -e 's,%s,[[previous version]],'" % (tmpfile, specfile,tmpfile))
1340 for module in new_modules:
1341 print '=== %s : new package in build %s ===' % (tagfile, module)
1343 for module in removed_modules:
1344 print '=== %s : removed package from build %s ===' % (tagfile, module)
1347 def adopt_tag (options, args):
1349 for module in options.modules:
1350 modules += module.split()
1351 for module in modules:
1352 modobj=Module(module,options)
1353 for tags_file in args:
1355 print 'adopting tag %s for %s in %s'%(options.tag,module,tags_file)
1356 modobj.patch_tags_file(tags_file,'_unused_',options.tag,fine_grain=False)
1358 Command("git diff %s"%" ".join(args),options).run()
1360 ##############################
1363 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1365 module-tools : a set of tools to manage subversion tags and specfile
1366 requires the specfile to either
1367 * define *version* and *taglevel*
1369 * define redirection variables module_version_varname / module_taglevel_varname
1371 by default, the trunk of modules is taken into account
1372 in this case, just mention the module name as <module_desc>
1374 if you wish to work on a branch rather than on the trunk,
1375 you can use something like e.g. Mom:2.1 as <module_desc>
1377 release_usage="""Usage: %prog [options] tag1 .. tagn
1378 Extract release notes from the changes in specfiles between several build tags, latest first
1380 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1381 You can refer to a (build) branch by prepending a colon, like in
1382 release-changelog :4.2 4.2-rc25
1383 You can refer to the build trunk by just mentioning 'trunk', e.g.
1384 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1386 adopt_usage="""Usage: %prog [options] tag-file[s]
1387 With this command you can adopt a specifi tag or branch in your tag files
1388 This should be run in your daily build workdir; no call of git nor svn is done
1390 adopt-tag -m "plewww plcapi" -m Monitor onelab*tags.mk
1391 adopt-tag -m sfa -t sfa-1.0-33 *tags.mk
1393 common_usage="""More help:
1394 see http://svn.planet-lab.org/wiki/ModuleTools"""
1397 'list' : "displays a list of available tags or branches",
1398 'version' : "check latest specfile and print out details",
1399 'diff' : "show difference between module (trunk or branch) and latest tag",
1400 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1401 create new tag and and monitor its adoption in build/*-tags.mk""",
1402 'branch' : """create a branch for this module, from the latest tag on the trunk,
1403 and change trunk's version number to reflect the new branch name;
1404 you can specify the new branch name by using module:branch""",
1405 'sync' : """create a tag from the module
1406 this is a last resort option, mostly for repairs""",
1407 'changelog' : """extract changelog between build tags
1408 expected arguments are a list of tags""",
1409 'adopt' : """locally adopt a specific tag""",
1412 silent_modes = ['list']
1413 # 'changelog' is for release-changelog
1414 # 'adopt' is for 'adopt-tag'
1415 regular_modes = set(modes.keys()).difference(set(['changelog','adopt']))
1418 def optparse_list (option, opt, value, parser):
1420 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1422 setattr(parser.values,option.dest,value.split())
1427 # hack - need to check for adopt first as 'adopt-tag' contains tag..
1428 for function in [ 'adopt' ] + Main.modes.keys():
1429 if sys.argv[0].find(function) >= 0:
1433 print "Unsupported command",sys.argv[0]
1434 print "Supported commands:" + " ".join(Main.modes.keys())
1437 usage='undefined usage, mode=%s'%mode
1438 if mode in Main.regular_modes:
1439 usage = Main.module_usage
1440 usage += Main.common_usage
1441 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1442 elif mode=='changelog':
1443 usage = Main.release_usage
1444 usage += Main.common_usage
1446 usage = Main.adopt_usage
1447 usage += Main.common_usage
1449 parser=OptionParser(usage=usage)
1451 # the 'adopt' mode is really special and doesn't share any option
1453 parser.add_option("-m","--module",action="append",dest="modules",default=[],
1454 help="modules, can be used several times or with quotes")
1455 parser.add_option("-t","--tag",action="store", dest="tag", default='master',
1456 help="specify the tag to adopt, default is 'master'")
1457 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1458 help="run in verbose mode")
1459 (options, args) = parser.parse_args()
1460 options.workdir='unused'
1461 options.dry_run=False
1462 options.mode='adopt'
1463 if len(args)==0 or len(options.modules)==0:
1466 adopt_tag (options,args)
1469 # the other commands (module-* and release-changelog) share the same skeleton
1470 if mode == "tag" or mode == 'branch':
1471 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1472 help="set new version and reset taglevel to 0")
1474 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1475 help="do not update changelog section in specfile when tagging")
1476 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1477 help="specify a build branch; used for locating the *tags.mk files where adoption is to take place")
1478 if mode == "tag" or mode == "sync" :
1479 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1480 help="specify editor")
1482 if mode in ["diff","version"] :
1483 parser.add_option("-W","--www", action="store", dest="www", default=False,
1484 help="export diff in html format, e.g. -W trunk")
1487 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1488 help="just list modules that exhibit differences")
1490 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1491 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1492 help="run on all modules as found in %s"%default_modules_list)
1493 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1494 help="run on all modules found in specified file")
1495 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1496 help="dry run - shell commands are only displayed")
1497 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1498 default=[], nargs=1,type="string",
1499 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1500 -- can be set multiple times, or use quotes""")
1502 parser.add_option("-w","--workdir", action="store", dest="workdir",
1503 default="%s/%s"%(os.getenv("HOME"),"modules"),
1504 help="""name for dedicated working dir - defaults to ~/modules
1505 ** THIS MUST NOT ** be your usual working directory""")
1506 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1507 help="skip safety checks, such as svn updates -- use with care")
1508 parser.add_option("-B","--build-module",action="store",dest="build_module",default=None,
1509 help="specify a build module to owerride the one in the CONFIG")
1511 # default verbosity depending on function - temp
1512 verbose_modes= ['tag', 'sync', 'branch']
1514 if mode not in verbose_modes:
1515 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1516 help="run in verbose mode")
1518 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1519 help="run in quiet (non-verbose) mode")
1520 (options, args) = parser.parse_args()
1522 if not hasattr(options,'dry_run'):
1523 options.dry_run=False
1524 if not hasattr(options,'www'):
1532 if options.all_modules:
1533 options.modules_list=default_modules_list
1534 if options.modules_list:
1535 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1539 Module.init_homedir(options)
1542 if mode in Main.regular_modes:
1543 modules=[ Module(modname,options) for modname in args ]
1544 # hack: create a dummy Module to store errors/warnings
1545 error_module = Module('__errors__',options)
1547 for module in modules:
1548 if len(args)>1 and mode not in Main.silent_modes:
1550 print '========================================',module.friendly_name()
1551 # call the method called do_<mode>
1552 method=Module.__dict__["do_%s"%mode]
1557 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1558 (module.friendly_name(), str(e))
1559 error_module.html_store_title(title)
1562 traceback.print_exc()
1563 print 'Skipping module %s: '%modname,e
1567 modetitle="Changes to tag in %s"%options.www
1568 elif mode == "version":
1569 modetitle="Latest tags in %s"%options.www
1570 modules.append(error_module)
1571 error_module.html_dump_header(modetitle)
1572 for module in modules:
1573 module.html_dump_toc()
1574 Module.html_dump_middle()
1575 for module in modules:
1576 module.html_dump_body()
1577 Module.html_dump_footer()
1579 # if we provide, say a b c d, we want to build (a,b) (b,c) and (c,d)
1580 # remember that the changelog in the twiki comes latest first, so
1581 # we typically have here latest latest-1 latest-2
1582 for (tag_to,tag_from) in zip ( args[:-1], args [1:]):
1583 release_changelog(options, tag_from,tag_to)
1586 ####################
1587 if __name__ == "__main__" :
1590 except KeyboardInterrupt: