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",
19 "VserverReference": "vserver-reference",
20 "BootstrapFS": "bootstrapfs",
23 "NodeManager": "nodemanager",
24 "NodeUpdate": "nodeupdate",
28 def svn_to_git_name(module):
29 if RENAMED_SVN_MODULES.has_key(module):
30 return RENAMED_SVN_MODULES[module]
33 def git_to_svn_name(module):
34 for key in RENAMED_SVN_MODULES:
35 if module == RENAMED_SVN_MODULES[key]:
40 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
41 def prompt (question,default=True,other_choices=[],allow_outside=False):
42 if not isinstance (other_choices,list):
43 other_choices = [ other_choices ]
44 chars = [ c for (c,rest) in other_choices ]
48 if default is True: choices.append('[y]')
49 else : choices.append('y')
51 if default is False: choices.append('[n]')
52 else : choices.append('n')
54 for (char,choice) in other_choices:
56 choices.append("["+char+"]"+choice)
58 choices.append("<"+char+">"+choice)
60 answer=raw_input(question + " " + "/".join(choices) + " ? ")
63 answer=answer[0].lower()
65 if 'y' in chars: return 'y'
68 if 'n' in chars: return 'n'
71 for (char,choice) in other_choices:
76 return prompt(question,default,other_choices)
82 editor = os.environ['EDITOR']
90 def print_fold (line):
91 while len(line) >= fold_length:
92 print line[:fold_length],'\\'
93 line=line[fold_length:]
97 def __init__ (self,command,options):
100 self.tmp="/tmp/command-%d"%os.getpid()
103 if self.options.dry_run:
104 print 'dry_run',self.command
106 if self.options.verbose and self.options.mode not in Main.silent_modes:
107 print '+',self.command
109 return os.system(self.command)
111 def run_silent (self):
112 if self.options.dry_run:
113 print 'dry_run',self.command
115 if self.options.verbose:
116 print '+',self.command,' .. ',
118 retcod=os.system(self.command + " &> " + self.tmp)
120 print "FAILED ! -- out+err below (command was %s)"%self.command
121 os.system("cat " + self.tmp)
122 print "FAILED ! -- end of quoted output"
123 elif self.options.verbose:
129 if self.run_silent() !=0:
130 raise Exception,"Command %s failed"%self.command
132 # returns stdout, like bash's $(mycommand)
133 def output_of (self,with_stderr=False):
134 if self.options.dry_run:
135 print 'dry_run',self.command
136 return 'dry_run output'
137 tmp="/tmp/status-%d"%os.getpid()
138 if self.options.debug:
139 print '+',self.command,' .. ',
148 result=file(tmp).read()
150 if self.options.debug:
158 def __init__(self, path, options):
160 self.options = options
163 return os.path.basename(self.path)
166 out = Command("svn info %s" % self.path, self.options).output_of()
167 for line in out.split('\n'):
168 if line.startswith("URL:"):
169 return line.split()[1].strip()
172 out = Command("svn info %s" % self.path, self.options).output_of()
173 for line in out.split('\n'):
174 if line.startswith("Repository Root:"):
175 root = line.split()[2].strip()
176 return "%s/%s" % (root, self.name())
179 def checkout(cls, remote, local, options, recursive=False):
181 svncommand = "svn co %s %s" % (remote, local)
183 svncommand = "svn co -N %s %s" % (remote, local)
184 Command("rm -rf %s" % local, options).run_silent()
185 Command(svncommand, options).run_fatal()
187 return SvnRepository(local, options)
190 def remote_exists(cls, remote):
191 return os.system("svn list %s &> /dev/null" % remote) == 0
193 def tag_exists(self, tagname):
194 url = "%s/tags/%s" % (self.repo_root(), tagname)
195 return SvnRepository.remote_exists(url)
197 def update(self, subdir="", recursive=True, branch=None):
198 path = os.path.join(self.path, subdir)
200 svncommand = "svn up %s" % path
202 svncommand = "svn up -N %s" % path
203 Command(svncommand, self.options).run_fatal()
205 def commit(self, logfile):
206 # add all new files to the repository
207 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
208 self.path, self.options).output_of()
209 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
211 def to_branch(self, branch):
212 remote = "%s/branches/%s" % (self.repo_root(), branch)
213 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
215 def to_tag(self, tag):
216 remote = "%s/tags/%s" % (self.repo_root(), branch)
217 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
219 def tag(self, tagname, logfile):
220 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
221 self_url = self.url()
222 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
224 def diff(self, f=""):
226 f = os.path.join(self.path, f)
229 return Command("svn diff %s" % f, self.options).output_of(True)
231 def diff_with_tag(self, tagname):
232 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
233 return Command("svn diff %s %s" % (tag_url, self.url()),
234 self.options).output_of(True)
236 def revert(self, f=""):
238 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
241 Command("svn revert %s -R" % self.path, self.options).run_fatal()
242 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
243 self.path, self.options).run_silent()
246 command="svn status %s" % self.path
247 return len(Command(command,self.options).output_of(True)) == 0
250 return os.path.exists(os.path.join(self.path, ".svn"))
256 def __init__(self, path, options):
258 self.options = options
261 return os.path.basename(self.path)
264 return self.repo_root()
267 c = Command("git show | grep commit | awk '{print $2;}'", self.options)
268 out = self.__run_in_repo(c.output_of).strip()
269 return "http://git.onelab.eu/?p=%s.git;a=commit;h=%s" % (self.name(), out)
272 c = Command("git remote show origin", self.options)
273 out = self.__run_in_repo(c.output_of)
274 for line in out.split('\n'):
275 if line.strip().startswith("Fetch URL:"):
276 return line.split()[2]
279 def checkout(cls, remote, local, options, depth=0):
280 Command("rm -rf %s" % local, options).run_silent()
281 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
282 return GitRepository(local, options)
285 def remote_exists(cls, remote):
286 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
288 def tag_exists(self, tagname):
289 command = 'git tag -l | grep "^%s$"' % tagname
290 c = Command(command, self.options)
291 out = self.__run_in_repo(c.output_of, with_stderr=True)
294 def __run_in_repo(self, fun, *args, **kwargs):
297 ret = fun(*args, **kwargs)
301 def __run_command_in_repo(self, command, ignore_errors=False):
302 c = Command(command, self.options)
304 return self.__run_in_repo(c.output_of)
306 return self.__run_in_repo(c.run_fatal)
308 def __is_commit_id(self, id):
309 c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
310 ret = self.__run_in_repo(c.output_of, with_stderr=False)
311 if ret.strip() == id:
315 def update(self, subdir=None, recursive=None, branch="master"):
316 if branch == "master":
317 self.__run_command_in_repo("git checkout %s" % branch)
319 self.to_branch(branch, remote=True)
320 self.__run_command_in_repo("git fetch origin --tags")
321 self.__run_command_in_repo("git fetch origin")
322 if not self.__is_commit_id(branch):
323 # we don't need to merge anythign for commit ids.
324 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
326 def to_branch(self, branch, remote=True):
329 command = "git branch --track %s origin/%s" % (branch, branch)
330 c = Command(command, self.options)
331 self.__run_in_repo(c.output_of, with_stderr=True)
332 return self.__run_command_in_repo("git checkout %s" % branch)
334 def to_tag(self, tag):
336 return self.__run_command_in_repo("git checkout %s" % tag)
338 def tag(self, tagname, logfile):
339 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
342 def diff(self, f=""):
343 c = Command("git diff %s" % f, self.options)
344 return self.__run_in_repo(c.output_of, with_stderr=True)
346 def diff_with_tag(self, tagname):
347 c = Command("git diff %s" % tagname, self.options)
348 return self.__run_in_repo(c.output_of, with_stderr=True)
350 def commit(self, logfile, branch="master"):
351 self.__run_command_in_repo("git add .", ignore_errors=True)
352 self.__run_command_in_repo("git add -u", ignore_errors=True)
353 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
354 if branch == "master" or self.__is_commit_id(branch):
355 self.__run_command_in_repo("git push")
357 self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
358 self.__run_command_in_repo("git push --tags")
360 def revert(self, f=""):
362 self.__run_command_in_repo("git checkout %s" % f)
365 self.__run_command_in_repo("git --no-pager reset --hard")
366 self.__run_command_in_repo("git --no-pager clean -f")
371 s="nothing to commit (working directory clean)"
372 return Command(command, self.options).output_of(True).find(s) >= 0
373 return self.__run_in_repo(check_commit)
376 return os.path.exists(os.path.join(self.path, ".git"))
380 """ Generic repository """
381 supported_repo_types = [SvnRepository, GitRepository]
383 def __init__(self, path, options):
385 self.options = options
386 for repo in self.supported_repo_types:
387 self.repo = repo(self.path, self.options)
388 if self.repo.is_valid():
392 def has_moved_to_git(cls, module, config):
393 module = svn_to_git_name(module)
394 # check if the module is already in Git
395 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
396 return GitRepository.remote_exists(Module.git_remote_dir(module))
400 def remote_exists(cls, remote):
401 for repo in Repository.supported_repo_types:
402 if repo.remote_exists(remote):
406 def __getattr__(self, attr):
407 return getattr(self.repo, attr)
411 # support for tagged module is minimal, and is for the Build class only
414 svn_magic_line="--This line, and those below, will be ignored--"
415 setting_tag_format = "Setting tag %s"
417 redirectors=[ # ('module_name_varname','name'),
418 ('module_version_varname','version'),
419 ('module_taglevel_varname','taglevel'), ]
421 # where to store user's config
422 config_storage="CONFIG"
427 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
428 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
429 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
430 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
431 ("build", "Enter the name of your build module","build"),
432 ('username',"Enter your firstname and lastname for changelogs",""),
433 ("email","Enter your email address for changelogs",""),
437 def prompt_config_option(cls, key, message, default):
438 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
441 def prompt_config (cls):
442 for (key,message,default) in cls.configKeys:
444 while not cls.config[key]:
445 cls.prompt_config_option(key, message, default)
447 # for parsing module spec name:branch
448 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
449 # special form for tagged module - for Build
450 matcher_tag_spec=re.compile("\A(?P<name>[\w\.-]+)@(?P<tagname>[\w\.-]+)\Z")
452 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
455 def parse_module_spec(cls, module_spec):
456 name = branch_or_tagname = module_type = ""
458 attempt=Module.matcher_branch_spec.match(module_spec)
460 module_type = "branch"
461 name=attempt.group('name')
462 branch_or_tagname=attempt.group('branch')
464 attempt=Module.matcher_tag_spec.match(module_spec)
467 name=attempt.group('name')
468 branch_or_tagname=attempt.group('tagname')
471 return name, branch_or_tagname, module_type
474 def __init__ (self,module_spec,options):
476 self.name, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
478 if module_type == "branch":
479 self.branch=branch_or_tagname
480 elif module_type == "tag":
481 self.tagname=branch_or_tagname
483 # when available prefer to use git module name internally
484 self.name = svn_to_git_name(self.name)
487 self.module_dir="%s/%s"%(options.workdir,self.name)
488 self.repository = None
491 def run (self,command):
492 return Command(command,self.options).run()
493 def run_fatal (self,command):
494 return Command(command,self.options).run_fatal()
495 def run_prompt (self,message,fun, *args):
496 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
497 if not self.options.verbose:
499 choice=prompt(message,True,('s','how'))
503 elif choice is False:
504 print 'About to run function:', fun_msg
506 question=message+" - want to run function: " + fun_msg
507 if prompt(question,True):
510 def friendly_name (self):
511 if hasattr(self,'branch'):
512 return "%s:%s"%(self.name,self.branch)
513 elif hasattr(self,'tagname'):
514 return "%s@%s"%(self.name,self.tagname)
519 def git_remote_dir (cls, name):
520 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
523 def svn_remote_dir (cls, name):
524 name = git_to_svn_name(name)
525 svn = cls.config['svnpath']
526 if svn.endswith('/'):
527 return "%s%s" % (svn, name)
528 return "%s/%s" % (svn, name)
530 def svn_selected_remote(self):
531 svn_name = git_to_svn_name(self.name)
532 remote = self.svn_remote_dir(svn_name)
533 if hasattr(self,'branch'):
534 remote = "%s/branches/%s" % (remote, self.branch)
535 elif hasattr(self,'tagname'):
536 remote = "%s/tags/%s" % (remote, self.tagname)
538 remote = "%s/trunk" % remote
543 def init_homedir (cls, options):
544 if options.verbose and options.mode not in Main.silent_modes:
545 print 'Checking for', options.workdir
546 storage="%s/%s"%(options.workdir, cls.config_storage)
547 # sanity check. Either the topdir exists AND we have a config/storage
548 # or topdir does not exist and we create it
549 # to avoid people use their own daily svn repo
550 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
551 print """The directory %s exists and has no CONFIG file
552 If this is your regular working directory, please provide another one as the
553 module-* commands need a fresh working dir. Make sure that you do not use
554 that for other purposes than tagging""" % options.workdir
557 def checkout_build():
558 print "Checking out build module..."
559 remote = cls.git_remote_dir(cls.config['build'])
560 local = os.path.join(options.workdir, cls.config['build'])
561 GitRepository.checkout(remote, local, options, depth=1)
566 for (key,message,default) in Module.configKeys:
567 f.write("%s=%s\n"%(key,Module.config[key]))
570 print 'Stored',storage
571 Command("cat %s"%storage,options).run()
576 for line in f.readlines():
577 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
578 Module.config[key]=value
581 if not os.path.isdir (options.workdir):
582 print "Cannot find",options.workdir,"let's create it"
583 Command("mkdir -p %s" % options.workdir, options).run_silent()
589 # check missing config options
591 for (key,message,default) in cls.configKeys:
592 if not Module.config.has_key(key):
593 print "Configuration changed for module-tools"
594 cls.prompt_config_option(key, message, default)
598 Command("rm -rf %s" % options.workdir, options).run_silent()
599 Command("mkdir -p %s" % options.workdir, options).run_silent()
603 build_dir = os.path.join(options.workdir, cls.config['build'])
604 if not os.path.isdir(build_dir):
607 build = Repository(build_dir, options)
608 if not build.is_clean():
609 print "build module needs a revert"
614 if options.verbose and options.mode not in Main.silent_modes:
615 print '******** Using config'
616 for (key,message,default) in Module.configKeys:
617 print '\t',key,'=',Module.config[key]
619 def init_module_dir (self):
620 if self.options.verbose:
621 print 'Checking for',self.module_dir
623 if not os.path.isdir (self.module_dir):
624 if Repository.has_moved_to_git(self.name, Module.config):
625 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
629 remote = self.svn_selected_remote()
630 self.repository = SvnRepository.checkout(remote,
632 self.options, recursive=False)
634 self.repository = Repository(self.module_dir, self.options)
635 if self.repository.type == "svn":
636 # check if module has moved to git
637 if Repository.has_moved_to_git(self.name, Module.config):
638 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
639 self.init_module_dir()
640 # check if we have the required branch/tag
641 if self.repository.url() != self.svn_selected_remote():
642 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
643 self.init_module_dir()
645 elif self.repository.type == "git":
646 if hasattr(self,'branch'):
647 self.repository.to_branch(self.branch)
648 elif hasattr(self,'tagname'):
649 self.repository.to_tag(self.tagname)
652 raise Exception, 'Cannot find %s - check module name'%self.module_dir
655 def revert_module_dir (self):
656 if self.options.fast_checks:
657 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
659 if self.options.verbose:
660 print 'Checking whether', self.module_dir, 'needs being reverted'
662 if not self.repository.is_clean():
663 self.repository.revert()
665 def update_module_dir (self):
666 if self.options.fast_checks:
667 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
669 if self.options.verbose:
670 print 'Updating', self.module_dir
672 if hasattr(self,'branch'):
673 self.repository.update(branch=self.branch)
674 elif hasattr(self,'tagname'):
675 self.repository.update(branch=self.tagname)
677 self.repository.update()
679 def main_specname (self):
680 attempt="%s/%s.spec"%(self.module_dir,self.name)
681 if os.path.isfile (attempt):
683 pattern1="%s/*.spec"%self.module_dir
684 level1=glob(pattern1)
687 pattern2="%s/*/*.spec"%self.module_dir
688 level2=glob(pattern2)
692 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
694 def all_specnames (self):
695 level1=glob("%s/*.spec" % self.module_dir)
696 if level1: return level1
697 level2=glob("%s/*/*.spec" % self.module_dir)
700 def parse_spec (self, specfile, varnames):
701 if self.options.verbose:
702 print 'Parsing',specfile,
708 for line in f.readlines():
709 attempt=Module.matcher_rpm_define.match(line)
711 (define,var,value)=attempt.groups()
715 if self.options.debug:
716 print 'found',len(result),'keys'
717 for (k,v) in result.iteritems():
721 # stores in self.module_name_varname the rpm variable to be used for the module's name
722 # and the list of these names in self.varnames
723 def spec_dict (self):
724 specfile=self.main_specname()
725 redirector_keys = [ varname for (varname,default) in Module.redirectors]
726 redirect_dict = self.parse_spec(specfile,redirector_keys)
727 if self.options.debug:
728 print '1st pass parsing done, redirect_dict=',redirect_dict
730 for (varname,default) in Module.redirectors:
731 if redirect_dict.has_key(varname):
732 setattr(self,varname,redirect_dict[varname])
733 varnames += [redirect_dict[varname]]
735 setattr(self,varname,default)
736 varnames += [ default ]
737 self.varnames = varnames
738 result = self.parse_spec (specfile,self.varnames)
739 if self.options.debug:
740 print '2st pass parsing done, varnames=',varnames,'result=',result
743 def patch_spec_var (self, patch_dict,define_missing=False):
744 for specfile in self.all_specnames():
745 # record the keys that were changed
746 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
747 newspecfile=specfile+".new"
748 if self.options.verbose:
749 print 'Patching',specfile,'for',patch_dict.keys()
751 new=open(newspecfile,"w")
753 for line in spec.readlines():
754 attempt=Module.matcher_rpm_define.match(line)
756 (define,var,value)=attempt.groups()
757 if var in patch_dict.keys():
758 if self.options.debug:
759 print 'rewriting %s as %s'%(var,patch_dict[var])
760 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
765 for (key,was_changed) in changed.iteritems():
767 if self.options.debug:
768 print 'rewriting missing %s as %s'%(key,patch_dict[key])
769 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
772 os.rename(newspecfile,specfile)
774 # returns all lines until the magic line
775 def unignored_lines (self, logfile):
777 white_line_matcher = re.compile("\A\s*\Z")
778 for logline in file(logfile).readlines():
779 if logline.strip() == Module.svn_magic_line:
781 elif white_line_matcher.match(logline):
784 result.append(logline.strip()+'\n')
787 # creates a copy of the input with only the unignored lines
788 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
790 f.write(self.setting_tag_format%new_tag_name + '\n')
791 for line in self.unignored_lines(filein):
795 def insert_changelog (self, logfile, oldtag, newtag):
796 for specfile in self.all_specnames():
797 newspecfile=specfile+".new"
798 if self.options.verbose:
799 print 'Inserting changelog from %s into %s'%(logfile,specfile)
801 new=open(newspecfile,"w")
802 for line in spec.readlines():
804 if re.compile('%changelog').match(line):
805 dateformat="* %a %b %d %Y"
806 datepart=time.strftime(dateformat)
807 logpart="%s <%s> - %s"%(Module.config['username'],
808 Module.config['email'],
810 new.write(datepart+" "+logpart+"\n")
811 for logline in self.unignored_lines(logfile):
812 new.write("- " + logline)
816 os.rename(newspecfile,specfile)
818 def show_dict (self, spec_dict):
819 if self.options.verbose:
820 for (k,v) in spec_dict.iteritems():
823 def last_tag (self, spec_dict):
825 return "%s-%s" % (spec_dict[self.module_version_varname],
826 spec_dict[self.module_taglevel_varname])
828 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
830 def tag_name (self, spec_dict, old_svn_name=False):
831 base_tag_name = self.name
833 base_tag_name = git_to_svn_name(self.name)
834 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
837 ##############################
838 # using fine_grain means replacing only those instances that currently refer to this tag
839 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
840 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
841 newtagsfile=tagsfile+".new"
843 new=open(newtagsfile,"w")
846 # fine-grain : replace those lines that refer to oldname
848 if self.options.verbose:
849 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
850 matcher=re.compile("^(.*)%s(.*)"%oldname)
851 for line in tags.readlines():
852 if not matcher.match(line):
855 (begin,end)=matcher.match(line).groups()
856 new.write(begin+newname+end+"\n")
858 # brute-force : change uncommented lines that define <module>-SVNPATH
860 if self.options.verbose:
861 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
862 pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
863 %(self.name,self.name)
864 matcher_module=re.compile(pattern)
865 for line in tags.readlines():
866 attempt=matcher_module.match(line)
868 if line.find("-GITPATH") >= 0:
869 modulepath = "%s-GITPATH"%self.name
870 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
872 modulepath = "%s-SVNPATH"%self.name
873 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
874 if self.options.verbose:
875 print ' ' + modulepath,
876 new.write(replacement)
882 os.rename(newtagsfile,tagsfile)
883 if self.options.verbose: print "%d changes"%matches
886 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
887 if self.options.verbose:
888 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
890 found_tagname = tagname
891 found = self.repository.tag_exists(tagname)
892 if not found and old_svn_tag_name:
893 if self.options.verbose:
895 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
896 found = self.repository.tag_exists(old_svn_tag_name)
898 found_tagname = old_svn_tag_name
900 if (found and need_it) or (not found and not need_it):
901 if self.options.verbose:
903 if found: print "- found"
904 else: print "- not found"
906 if self.options.verbose:
909 raise Exception, "tag (%s) is already there" % tagname
911 raise Exception, "can not find required tag (%s)" % tagname
916 ##############################
918 self.init_module_dir()
919 self.revert_module_dir()
920 self.update_module_dir()
922 spec_dict = self.spec_dict()
923 self.show_dict(spec_dict)
926 old_tag_name = self.tag_name(spec_dict)
927 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
929 if (self.options.new_version):
930 # new version set on command line
931 spec_dict[self.module_version_varname] = self.options.new_version
932 spec_dict[self.module_taglevel_varname] = 0
935 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
936 spec_dict[self.module_taglevel_varname] = new_taglevel
938 new_tag_name = self.tag_name(spec_dict)
941 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
942 new_tag_name = self.check_tag(new_tag_name, need_it=False)
945 diff_output = self.repository.diff_with_tag(old_tag_name)
946 if len(diff_output) == 0:
947 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
950 # side effect in trunk's specfile
951 self.patch_spec_var(spec_dict)
953 # prepare changelog file
954 # we use the standard subversion magic string (see svn_magic_line)
955 # so we can provide useful information, such as version numbers and diff
957 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
958 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
959 setting_tag_line=Module.setting_tag_format%new_tag_name
960 file(changelog,"w").write("""
963 Please write a changelog for this new tag in the section above
964 """%(Module.svn_magic_line,setting_tag_line))
966 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
967 file(changelog,"a").write('DIFF=========\n' + diff_output)
969 if self.options.debug:
973 self.run("%s %s"%(self.options.editor,changelog))
974 # strip magic line in second file - looks like svn has changed its magic line with 1.6
975 # so we do the job ourselves
976 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
977 # insert changelog in spec
978 if self.options.changelog:
979 self.insert_changelog (changelog,old_tag_name,new_tag_name)
982 build_path = os.path.join(self.options.workdir,
983 Module.config['build'])
984 build = Repository(build_path, self.options)
985 if self.options.build_branch:
986 build.to_branch(self.options.build_branch)
987 if not build.is_clean():
990 tagsfiles=glob(build.path+"/*-tags.mk")
991 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
995 for tagsfile in tagsfiles:
996 status=tagsdict[tagsfile]
997 basename=os.path.basename(tagsfile)
998 print ".................... Dealing with %s"%basename
999 while tagsdict[tagsfile] == 'todo' :
1000 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
1001 [ ('y','es'), ('n', 'ext'), ('f','orce'),
1002 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
1005 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1007 print 'Done with %s'%os.path.basename(tagsfile)
1008 tagsdict[tagsfile]='done'
1010 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1012 print build.diff(f=os.path.basename(tagsfile))
1014 build.revert(f=tagsfile)
1016 self.run("cat %s"%tagsfile)
1019 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1020 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1021 d: show current diff for this tag file
1022 r: revert that tag file
1023 c: cat the current tag file
1024 n: move to next file"""%locals()
1026 if prompt("Want to review changes on tags files",False):
1027 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1032 def diff_all_changes():
1034 print self.repository.diff()
1036 def commit_all_changes(log):
1037 if hasattr(self,'branch'):
1038 self.repository.commit(log, branch=self.branch)
1040 self.repository.commit(log)
1043 self.run_prompt("Review module and build", diff_all_changes)
1044 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1045 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1047 if self.options.debug:
1048 print 'Preserving',changelog,'and stripped',changelog_svn
1050 os.unlink(changelog)
1051 os.unlink(changelog_svn)
1054 ##############################
1055 def do_version (self):
1056 self.init_module_dir()
1057 self.revert_module_dir()
1058 self.update_module_dir()
1059 spec_dict = self.spec_dict()
1060 if self.options.www:
1061 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1062 self.last_tag(spec_dict)))
1063 for varname in self.varnames:
1064 if not spec_dict.has_key(varname):
1065 self.html_print ('Could not find %%define for %s'%varname)
1068 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1069 self.html_print ("%-16s %s"%('url',self.repository.url()))
1070 if self.options.verbose:
1071 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1072 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1073 self.html_print_end()
1076 ##############################
1078 self.init_module_dir()
1079 self.revert_module_dir()
1080 self.update_module_dir()
1081 spec_dict = self.spec_dict()
1082 self.show_dict(spec_dict)
1085 tag_name = self.tag_name(spec_dict)
1086 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1089 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1091 if self.options.verbose:
1092 print 'Getting diff'
1093 diff_output = self.repository.diff_with_tag(tag_name)
1095 if self.options.list:
1099 thename=self.friendly_name()
1101 if self.options.www and diff_output:
1102 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1103 thename,self.last_tag(spec_dict),len(diff_output)))
1105 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1106 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1107 self.html_store_pre (diff_output)
1108 elif not self.options.www:
1109 print 'x'*30,'module',thename
1110 print 'x'*20,'<',tag_name
1111 print 'x'*20,'>',thename
1114 ##############################
1115 # store and restitute html fragments
1117 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1120 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1123 def html_quote (text):
1124 return text.replace('&','&').replace('<','<').replace('>','>')
1126 # only the fake error module has multiple titles
1127 def html_store_title (self, title):
1128 if not hasattr(self,'titles'): self.titles=[]
1129 self.titles.append(title)
1131 def html_store_raw (self, html):
1132 if not hasattr(self,'body'): self.body=''
1135 def html_store_pre (self, text):
1136 if not hasattr(self,'body'): self.body=''
1137 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1139 def html_print (self, txt):
1140 if not self.options.www:
1143 if not hasattr(self,'in_list') or not self.in_list:
1144 self.html_store_raw('<ul>')
1146 self.html_store_raw('<li>'+txt+'</li>')
1148 def html_print_end (self):
1149 if self.options.www:
1150 self.html_store_raw ('</ul>')
1153 def html_dump_header(title):
1154 nowdate=time.strftime("%Y-%m-%d")
1155 nowtime=time.strftime("%H:%M (%Z)")
1156 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1157 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1160 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1161 <style type="text/css">
1162 body { font-family:georgia, serif; }
1163 h1 {font-size: large; }
1164 p.title {font-size: x-large; }
1165 span.error {text-weight:bold; color: red; }
1169 <p class='title'> %s - status on %s at %s</p>
1171 """%(title,title,nowdate,nowtime)
1174 def html_dump_middle():
1178 def html_dump_footer():
1179 print "</body></html"
1181 def html_dump_toc(self):
1182 if hasattr(self,'titles'):
1183 for title in self.titles:
1184 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1186 def html_dump_body(self):
1187 if hasattr(self,'titles'):
1188 for title in self.titles:
1189 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1190 if hasattr(self,'body'):
1192 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1196 class Build(Module):
1198 def __get_modules(self, tagfile):
1199 self.init_module_dir()
1202 tagfile = os.path.join(self.module_dir, tagfile)
1203 for line in open(tagfile):
1205 name, url = line.split(':=')
1206 name, git_or_svn_path = name.rsplit('-', 1)
1207 name = svn_to_git_name(name.strip())
1208 modules[name] = (git_or_svn_path.strip(), url.strip())
1213 def get_modules(self, tagfile):
1214 modules = self.__get_modules(tagfile)
1215 for module in modules:
1216 module_type = tag_or_branch = ""
1218 path_type, url = modules[module]
1219 if path_type == "GITPATH":
1220 module_spec = os.path.split(url)[-1].replace(".git","")
1221 name, tag_or_branch, module_type = self.parse_module_spec(module_spec)
1223 tag_or_branch = os.path.split(url)[-1].strip()
1224 if url.find('/tags/') >= 0:
1226 elif url.find('/branches/') >= 0:
1227 module_type = "branch"
1229 modules[module] = {"module_type" : module_type,
1230 "path_type": path_type,
1231 "tag_or_branch": tag_or_branch,
1237 def modules_diff(first, second):
1240 for module in first:
1241 if module not in second:
1242 print "=== module %s missing in right-hand side ==="%module
1244 if first[module]['tag_or_branch'] != second[module]['tag_or_branch']:
1245 diff[module] = (first[module]['tag_or_branch'], second[module]['tag_or_branch'])
1247 first_set = set(first.keys())
1248 second_set = set(second.keys())
1250 new_modules = list(second_set - first_set)
1251 removed_modules = list(first_set - second_set)
1253 return diff, new_modules, removed_modules
1255 def release_changelog(options, buildtag_old, buildtag_new):
1257 tagfile = options.distrotags[0]
1259 print "ERROR: provide a tagfile name (eg. onelab, onelab-k27, planetlab)"
1261 tagfile = "%s-tags.mk" % tagfile
1266 print '= build tag %s to %s =' % (buildtag_old, buildtag_new)
1267 print '== distro %s (%s to %s) ==' % (tagfile, buildtag_old, buildtag_new)
1269 build = Build("build@%s" % buildtag_old, options)
1270 build.init_module_dir()
1271 first = build.get_modules(tagfile)
1273 print ' * from', buildtag_old, build.repository.gitweb()
1275 build = Build("build@%s" % buildtag_new, options)
1276 build.init_module_dir()
1277 second = build.get_modules(tagfile)
1279 print ' * to', buildtag_new, build.repository.gitweb()
1281 diff, new_modules, removed_modules = modules_diff(first, second)
1284 def get_module(name, tag):
1285 if not tag or tag == "trunk":
1286 return Module("%s" % (module), options)
1288 return Module("%s@%s" % (module, tag), options)
1292 print '=== %s - %s to %s : package %s ===' % (tagfile, buildtag_old, buildtag_new, module)
1294 first, second = diff[module]
1295 m = get_module(module, first)
1296 os.system('rm -rf %s' % m.module_dir) # cleanup module dir
1299 if m.repository.type == "svn":
1300 print ' * from', first, m.repository.url()
1302 print ' * from', first, m.repository.gitweb()
1304 specfile = m.main_specname()
1305 (tmpfd, tmpfile) = tempfile.mkstemp()
1306 os.system("cp -f /%s %s" % (specfile, tmpfile))
1308 m = get_module(module, second)
1310 specfile = m.main_specname()
1312 if m.repository.type == "svn":
1313 print ' * to', second, m.repository.url()
1315 print ' * to', second, m.repository.gitweb()
1318 os.system("diff -u %s %s" % (tmpfile, specfile))
1323 for module in new_modules:
1324 print '=== %s : new package in build %s ===' % (tagfile, module)
1326 for module in removed_modules:
1327 print '=== %s : removed package from build %s ===' % (tagfile, module)
1330 def adopt_master (options, args):
1332 for module in options.modules:
1333 modules += module.split()
1334 for module in modules:
1335 modobj=Module(module,options)
1336 for tags_file in args:
1338 print 'adopting master for',module,'in',tags_file
1339 modobj.patch_tags_file(tags_file,'_unused_','master',fine_grain=False)
1341 Command("git diff %s"%" ".join(args),options).run()
1343 ##############################
1346 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1348 module-tools : a set of tools to manage subversion tags and specfile
1349 requires the specfile to either
1350 * define *version* and *taglevel*
1352 * define redirection variables module_version_varname / module_taglevel_varname
1354 by default, the trunk of modules is taken into account
1355 in this case, just mention the module name as <module_desc>
1357 if you wish to work on a branch rather than on the trunk,
1358 you can use something like e.g. Mom:2.1 as <module_desc>
1360 release_usage="""Usage: %prog [options] tag1 .. tagn
1361 Extract release notes from the changes in specfiles between several build tags, latest first
1363 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1364 You can refer to a (build) branch by prepending a colon, like in
1365 release-changelog :4.2 4.2-rc25
1366 You can refer to the build trunk by just mentioning 'trunk', e.g.
1367 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1369 master_usage="""Usage: %prog [options] tag-file[s]
1370 With this command you can adopt one or several masters in your tag files
1371 This should be run in your daily build workdir; no call of git nor svn is done
1373 module-master -m "plewww plcapi" -m Monitor onelab*tags.mk
1375 common_usage="""More help:
1376 see http://svn.planet-lab.org/wiki/ModuleTools"""
1379 'list' : "displays a list of available tags or branches",
1380 'version' : "check latest specfile and print out details",
1381 'diff' : "show difference between module (trunk or branch) and latest tag",
1382 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1383 create new tag and and monitor its adoption in build/*-tags.mk""",
1384 'branch' : """create a branch for this module, from the latest tag on the trunk,
1385 and change trunk's version number to reflect the new branch name;
1386 you can specify the new branch name by using module:branch""",
1387 'sync' : """create a tag from the module
1388 this is a last resort option, mostly for repairs""",
1389 'changelog' : """extract changelog between build tags
1390 expected arguments are a list of tags""",
1391 'master' : """locally adopt master or trunk for some modules""",
1394 silent_modes = ['list']
1395 # 'changelog' is for release-changelog
1396 # 'master' is for 'adopt-master'
1397 regular_modes = set(modes.keys()).difference(set(['changelog','master']))
1400 def optparse_list (option, opt, value, parser):
1402 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1404 setattr(parser.values,option.dest,value.split())
1409 for function in Main.modes.keys():
1410 if sys.argv[0].find(function) >= 0:
1414 print "Unsupported command",sys.argv[0]
1415 print "Supported commands:" + " ".join(Main.modes.keys())
1418 usage='undefined usage, mode=%s'%mode
1419 if mode in Main.regular_modes:
1420 usage = Main.module_usage
1421 usage += Main.common_usage
1422 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1423 elif mode=='changelog':
1424 usage = Main.release_usage
1425 usage += Main.common_usage
1426 elif mode=='master':
1427 usage = Main.master_usage
1428 usage += Main.common_usage
1430 parser=OptionParser(usage=usage)
1432 # the 'master' mode is really special and doesn't share any option
1434 parser.add_option("-m","--module",action="append",dest="modules",default=[],
1435 help="modules, can be used several times or with quotes")
1436 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1437 help="run in verbose mode")
1438 (options, args) = parser.parse_args()
1439 options.workdir='unused'
1440 options.dry_run=False
1441 options.mode='master'
1442 if len(args)==0 or len(options.modules)==0:
1445 adopt_master (options,args)
1448 # the other commands (module-* and release-changelog) share the same skeleton
1449 if mode == "tag" or mode == 'branch':
1450 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1451 help="set new version and reset taglevel to 0")
1453 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1454 help="do not update changelog section in specfile when tagging")
1455 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1456 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1457 if mode == "tag" or mode == "sync" :
1458 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1459 help="specify editor")
1461 if mode in ["diff","version"] :
1462 parser.add_option("-W","--www", action="store", dest="www", default=False,
1463 help="export diff in html format, e.g. -W trunk")
1466 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1467 help="just list modules that exhibit differences")
1469 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1470 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1471 help="run on all modules as found in %s"%default_modules_list)
1472 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1473 help="run on all modules found in specified file")
1474 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1475 help="dry run - shell commands are only displayed")
1476 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1477 default=[], nargs=1,type="string",
1478 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1479 -- can be set multiple times, or use quotes""")
1481 parser.add_option("-w","--workdir", action="store", dest="workdir",
1482 default="%s/%s"%(os.getenv("HOME"),"modules"),
1483 help="""name for dedicated working dir - defaults to ~/modules
1484 ** THIS MUST NOT ** be your usual working directory""")
1485 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1486 help="skip safety checks, such as svn updates -- use with care")
1488 # default verbosity depending on function - temp
1489 verbose_modes= ['tag', 'sync', 'branch']
1491 if mode not in verbose_modes:
1492 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1493 help="run in verbose mode")
1495 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1496 help="run in quiet (non-verbose) mode")
1497 (options, args) = parser.parse_args()
1499 if not hasattr(options,'dry_run'):
1500 options.dry_run=False
1501 if not hasattr(options,'www'):
1509 if options.all_modules:
1510 options.modules_list=default_modules_list
1511 if options.modules_list:
1512 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1516 Module.init_homedir(options)
1519 if mode in Main.regular_modes:
1520 modules=[ Module(modname,options) for modname in args ]
1521 # hack: create a dummy Module to store errors/warnings
1522 error_module = Module('__errors__',options)
1524 for module in modules:
1525 if len(args)>1 and mode not in Main.silent_modes:
1527 print '========================================',module.friendly_name()
1528 # call the method called do_<mode>
1529 method=Module.__dict__["do_%s"%mode]
1534 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1535 (module.friendly_name(), str(e))
1536 error_module.html_store_title(title)
1539 traceback.print_exc()
1540 print 'Skipping module %s: '%modname,e
1544 modetitle="Changes to tag in %s"%options.www
1545 elif mode == "version":
1546 modetitle="Latest tags in %s"%options.www
1547 modules.append(error_module)
1548 error_module.html_dump_header(modetitle)
1549 for module in modules:
1550 module.html_dump_toc()
1551 Module.html_dump_middle()
1552 for module in modules:
1553 module.html_dump_body()
1554 Module.html_dump_footer()
1556 release_changelog(options, *args)
1559 ####################
1560 if __name__ == "__main__" :
1563 except KeyboardInterrupt: