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",
29 def svn_to_git_name(module):
30 if RENAMED_SVN_MODULES.has_key(module):
31 return RENAMED_SVN_MODULES[module]
34 def git_to_svn_name(module):
35 for key in RENAMED_SVN_MODULES:
36 if module == RENAMED_SVN_MODULES[key]:
41 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
42 def prompt (question,default=True,other_choices=[],allow_outside=False):
43 if not isinstance (other_choices,list):
44 other_choices = [ other_choices ]
45 chars = [ c for (c,rest) in other_choices ]
49 if default is True: choices.append('[y]')
50 else : choices.append('y')
52 if default is False: choices.append('[n]')
53 else : choices.append('n')
55 for (char,choice) in other_choices:
57 choices.append("["+char+"]"+choice)
59 choices.append("<"+char+">"+choice)
61 answer=raw_input(question + " " + "/".join(choices) + " ? ")
64 answer=answer[0].lower()
66 if 'y' in chars: return 'y'
69 if 'n' in chars: return 'n'
72 for (char,choice) in other_choices:
77 return prompt(question,default,other_choices)
83 editor = os.environ['EDITOR']
91 def print_fold (line):
92 while len(line) >= fold_length:
93 print line[:fold_length],'\\'
94 line=line[fold_length:]
98 def __init__ (self,command,options):
101 self.tmp="/tmp/command-%d"%os.getpid()
104 if self.options.dry_run:
105 print 'dry_run',self.command
107 if self.options.verbose and self.options.mode not in Main.silent_modes:
108 print '+',self.command
110 return os.system(self.command)
112 def run_silent (self):
113 if self.options.dry_run:
114 print 'dry_run',self.command
116 if self.options.verbose:
117 print '+',self.command,' .. ',
119 retcod=os.system(self.command + " &> " + self.tmp)
121 print "FAILED ! -- out+err below (command was %s)"%self.command
122 os.system("cat " + self.tmp)
123 print "FAILED ! -- end of quoted output"
124 elif self.options.verbose:
130 if self.run_silent() !=0:
131 raise Exception,"Command %s failed"%self.command
133 # returns stdout, like bash's $(mycommand)
134 def output_of (self,with_stderr=False):
135 if self.options.dry_run:
136 print 'dry_run',self.command
137 return 'dry_run output'
138 tmp="/tmp/status-%d"%os.getpid()
139 if self.options.debug:
140 print '+',self.command,' .. ',
149 result=file(tmp).read()
151 if self.options.debug:
159 def __init__(self, path, options):
161 self.options = options
164 return os.path.basename(self.path)
167 # for svn modules pathname is just the name of the module as
168 # all modules are at the root
172 out = Command("svn info %s" % self.path, self.options).output_of()
173 for line in out.split('\n'):
174 if line.startswith("URL:"):
175 return line.split()[1].strip()
178 out = Command("svn info %s" % self.path, self.options).output_of()
179 for line in out.split('\n'):
180 if line.startswith("Repository Root:"):
181 root = line.split()[2].strip()
182 return "%s/%s" % (root, self.pathname())
185 def checkout(cls, remote, local, options, recursive=False):
187 svncommand = "svn co %s %s" % (remote, local)
189 svncommand = "svn co -N %s %s" % (remote, local)
190 Command("rm -rf %s" % local, options).run_silent()
191 Command(svncommand, options).run_fatal()
193 return SvnRepository(local, options)
196 def remote_exists(cls, remote):
197 return os.system("svn list %s &> /dev/null" % remote) == 0
199 def tag_exists(self, tagname):
200 url = "%s/tags/%s" % (self.repo_root(), tagname)
201 return SvnRepository.remote_exists(url)
203 def update(self, subdir="", recursive=True, branch=None):
204 path = os.path.join(self.path, subdir)
206 svncommand = "svn up %s" % path
208 svncommand = "svn up -N %s" % path
209 Command(svncommand, self.options).run_fatal()
211 def commit(self, logfile):
212 # add all new files to the repository
213 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
214 self.path, self.options).output_of()
215 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
217 def to_branch(self, branch):
218 remote = "%s/branches/%s" % (self.repo_root(), branch)
219 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
221 def to_tag(self, tag):
222 remote = "%s/tags/%s" % (self.repo_root(), branch)
223 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
225 def tag(self, tagname, logfile):
226 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
227 self_url = self.url()
228 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
230 def diff(self, f=""):
232 f = os.path.join(self.path, f)
235 return Command("svn diff %s" % f, self.options).output_of(True)
237 def diff_with_tag(self, tagname):
238 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
239 return Command("svn diff %s %s" % (tag_url, self.url()),
240 self.options).output_of(True)
242 def revert(self, f=""):
244 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
247 Command("svn revert %s -R" % self.path, self.options).run_fatal()
248 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
249 self.path, self.options).run_silent()
252 command="svn status %s" % self.path
253 return len(Command(command,self.options).output_of(True)) == 0
256 return os.path.exists(os.path.join(self.path, ".svn"))
262 def __init__(self, path, options):
264 self.options = options
267 return os.path.basename(self.path)
270 return self.repo_root()
273 c = Command("git show | grep commit | awk '{print $2;}'", self.options)
274 out = self.__run_in_repo(c.output_of).strip()
275 return "http://git.onelab.eu/?p=%s.git;a=commit;h=%s" % (self.name(), out)
278 c = Command("git remote show origin", self.options)
279 out = self.__run_in_repo(c.output_of)
280 for line in out.split('\n'):
281 if line.strip().startswith("Fetch URL:"):
282 return line.split()[2]
285 def checkout(cls, remote, local, options, depth=0):
286 Command("rm -rf %s" % local, options).run_silent()
287 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
288 return GitRepository(local, options)
291 def remote_exists(cls, remote):
292 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
294 def tag_exists(self, tagname):
295 command = 'git tag -l | grep "^%s$"' % tagname
296 c = Command(command, self.options)
297 out = self.__run_in_repo(c.output_of, with_stderr=True)
300 def __run_in_repo(self, fun, *args, **kwargs):
303 ret = fun(*args, **kwargs)
307 def __run_command_in_repo(self, command, ignore_errors=False):
308 c = Command(command, self.options)
310 return self.__run_in_repo(c.output_of)
312 return self.__run_in_repo(c.run_fatal)
314 def __is_commit_id(self, id):
315 c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
316 ret = self.__run_in_repo(c.output_of, with_stderr=False)
317 if ret.strip() == id:
321 def update(self, subdir=None, recursive=None, branch="master"):
322 if branch == "master":
323 self.__run_command_in_repo("git checkout %s" % branch)
325 self.to_branch(branch, remote=True)
326 self.__run_command_in_repo("git fetch origin --tags")
327 self.__run_command_in_repo("git fetch origin")
328 if not self.__is_commit_id(branch):
329 # we don't need to merge anythign for commit ids.
330 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
332 def to_branch(self, branch, remote=True):
335 command = "git branch --track %s origin/%s" % (branch, branch)
336 c = Command(command, self.options)
337 self.__run_in_repo(c.output_of, with_stderr=True)
338 return self.__run_command_in_repo("git checkout %s" % branch)
340 def to_tag(self, tag):
342 return self.__run_command_in_repo("git checkout %s" % tag)
344 def tag(self, tagname, logfile):
345 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
348 def diff(self, f=""):
349 c = Command("git diff %s" % f, self.options)
350 return self.__run_in_repo(c.output_of, with_stderr=True)
352 def diff_with_tag(self, tagname):
353 c = Command("git diff %s" % tagname, self.options)
354 return self.__run_in_repo(c.output_of, with_stderr=True)
356 def commit(self, logfile, branch="master"):
357 self.__run_command_in_repo("git add .", ignore_errors=True)
358 self.__run_command_in_repo("git add -u", ignore_errors=True)
359 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
360 if branch == "master" or self.__is_commit_id(branch):
361 self.__run_command_in_repo("git push")
363 self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
364 self.__run_command_in_repo("git push --tags")
366 def revert(self, f=""):
368 self.__run_command_in_repo("git checkout %s" % f)
371 self.__run_command_in_repo("git --no-pager reset --hard")
372 self.__run_command_in_repo("git --no-pager clean -f")
377 s="nothing to commit (working directory clean)"
378 return Command(command, self.options).output_of(True).find(s) >= 0
379 return self.__run_in_repo(check_commit)
382 return os.path.exists(os.path.join(self.path, ".git"))
386 """ Generic repository """
387 supported_repo_types = [SvnRepository, GitRepository]
389 def __init__(self, path, options):
391 self.options = options
392 for repo in self.supported_repo_types:
393 self.repo = repo(self.path, self.options)
394 if self.repo.is_valid():
398 def has_moved_to_git(cls, module, config):
399 module = svn_to_git_name(module)
400 # check if the module is already in Git
401 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
402 return GitRepository.remote_exists(Module.git_remote_dir(module))
406 def remote_exists(cls, remote):
407 for repo in Repository.supported_repo_types:
408 if repo.remote_exists(remote):
412 def __getattr__(self, attr):
413 return getattr(self.repo, attr)
417 # support for tagged module is minimal, and is for the Build class only
420 svn_magic_line="--This line, and those below, will be ignored--"
421 setting_tag_format = "Setting tag %s"
423 redirectors=[ # ('module_name_varname','name'),
424 ('module_version_varname','version'),
425 ('module_taglevel_varname','taglevel'), ]
427 # where to store user's config
428 config_storage="CONFIG"
433 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
434 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
435 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
436 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
437 ("build", "Enter the name of your build module","build"),
438 ('username',"Enter your firstname and lastname for changelogs",""),
439 ("email","Enter your email address for changelogs",""),
443 def prompt_config_option(cls, key, message, default):
444 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
447 def prompt_config (cls):
448 for (key,message,default) in cls.configKeys:
450 while not cls.config[key]:
451 cls.prompt_config_option(key, message, default)
453 # for parsing module spec name:branch
454 matcher_branch_spec=re.compile("\A(?P<name>[\w\.\-\/]+):(?P<branch>[\w\.\-]+)\Z")
455 # special form for tagged module - for Build
456 matcher_tag_spec=re.compile("\A(?P<name>[\w\.\-\/]+)@(?P<tagname>[\w\.\-]+)\Z")
458 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
461 def parse_module_spec(cls, module_spec):
462 name = branch_or_tagname = module_type = ""
464 attempt=Module.matcher_branch_spec.match(module_spec)
466 module_type = "branch"
467 name=attempt.group('name')
468 branch_or_tagname=attempt.group('branch')
470 attempt=Module.matcher_tag_spec.match(module_spec)
473 name=attempt.group('name')
474 branch_or_tagname=attempt.group('tagname')
477 return name, branch_or_tagname, module_type
480 def __init__ (self,module_spec,options):
482 self.pathname, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
483 self.name = os.path.basename(self.pathname)
485 if module_type == "branch":
486 self.branch=branch_or_tagname
487 elif module_type == "tag":
488 self.tagname=branch_or_tagname
490 # when available prefer to use git module name internally
491 self.name = svn_to_git_name(self.name)
494 self.module_dir="%s/%s"%(options.workdir,self.pathname)
495 self.repository = None
498 def run (self,command):
499 return Command(command,self.options).run()
500 def run_fatal (self,command):
501 return Command(command,self.options).run_fatal()
502 def run_prompt (self,message,fun, *args):
503 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
504 if not self.options.verbose:
506 choice=prompt(message,True,('s','how'))
510 elif choice is False:
511 print 'About to run function:', fun_msg
513 question=message+" - want to run function: " + fun_msg
514 if prompt(question,True):
517 def friendly_name (self):
518 if hasattr(self,'branch'):
519 return "%s:%s"%(self.pathname,self.branch)
520 elif hasattr(self,'tagname'):
521 return "%s@%s"%(self.pathname,self.tagname)
526 def git_remote_dir (cls, name):
527 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
530 def svn_remote_dir (cls, name):
531 name = git_to_svn_name(name)
532 svn = cls.config['svnpath']
533 if svn.endswith('/'):
534 return "%s%s" % (svn, name)
535 return "%s/%s" % (svn, name)
537 def svn_selected_remote(self):
538 svn_name = git_to_svn_name(self.name)
539 remote = self.svn_remote_dir(svn_name)
540 if hasattr(self,'branch'):
541 remote = "%s/branches/%s" % (remote, self.branch)
542 elif hasattr(self,'tagname'):
543 remote = "%s/tags/%s" % (remote, self.tagname)
545 remote = "%s/trunk" % remote
550 def init_homedir (cls, options):
551 if options.verbose and options.mode not in Main.silent_modes:
552 print 'Checking for', options.workdir
553 storage="%s/%s"%(options.workdir, cls.config_storage)
554 # sanity check. Either the topdir exists AND we have a config/storage
555 # or topdir does not exist and we create it
556 # to avoid people use their own daily svn repo
557 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
558 print """The directory %s exists and has no CONFIG file
559 If this is your regular working directory, please provide another one as the
560 module-* commands need a fresh working dir. Make sure that you do not use
561 that for other purposes than tagging""" % options.workdir
564 def checkout_build():
565 print "Checking out build module..."
566 remote = cls.git_remote_dir(cls.config['build'])
567 local = os.path.join(options.workdir, cls.config['build'])
568 GitRepository.checkout(remote, local, options, depth=1)
573 for (key,message,default) in Module.configKeys:
574 f.write("%s=%s\n"%(key,Module.config[key]))
577 print 'Stored',storage
578 Command("cat %s"%storage,options).run()
583 for line in f.readlines():
584 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
585 Module.config[key]=value
588 # owerride config variables using options.
589 if options.build_module:
590 Module.config['build'] = options.build_module
592 if not os.path.isdir (options.workdir):
593 print "Cannot find",options.workdir,"let's create it"
594 Command("mkdir -p %s" % options.workdir, options).run_silent()
600 # check missing config options
602 for (key,message,default) in cls.configKeys:
603 if not Module.config.has_key(key):
604 print "Configuration changed for module-tools"
605 cls.prompt_config_option(key, message, default)
609 Command("rm -rf %s" % options.workdir, options).run_silent()
610 Command("mkdir -p %s" % options.workdir, options).run_silent()
614 build_dir = os.path.join(options.workdir, cls.config['build'])
615 if not os.path.isdir(build_dir):
618 build = Repository(build_dir, options)
619 if not build.is_clean():
620 print "build module needs a revert"
625 if options.verbose and options.mode not in Main.silent_modes:
626 print '******** Using config'
627 for (key,message,default) in Module.configKeys:
628 print '\t',key,'=',Module.config[key]
630 def init_module_dir (self):
631 if self.options.verbose:
632 print 'Checking for',self.module_dir
634 if not os.path.isdir (self.module_dir):
635 if Repository.has_moved_to_git(self.pathname, Module.config):
636 self.repository = GitRepository.checkout(self.git_remote_dir(self.pathname),
640 remote = self.svn_selected_remote()
641 self.repository = SvnRepository.checkout(remote,
643 self.options, recursive=False)
645 self.repository = Repository(self.module_dir, self.options)
646 if self.repository.type == "svn":
647 # check if module has moved to git
648 if Repository.has_moved_to_git(self.pathname, Module.config):
649 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
650 self.init_module_dir()
651 # check if we have the required branch/tag
652 if self.repository.url() != self.svn_selected_remote():
653 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
654 self.init_module_dir()
656 elif self.repository.type == "git":
657 if hasattr(self,'branch'):
658 self.repository.to_branch(self.branch)
659 elif hasattr(self,'tagname'):
660 self.repository.to_tag(self.tagname)
663 raise Exception, 'Cannot find %s - check module name'%self.module_dir
666 def revert_module_dir (self):
667 if self.options.fast_checks:
668 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
670 if self.options.verbose:
671 print 'Checking whether', self.module_dir, 'needs being reverted'
673 if not self.repository.is_clean():
674 self.repository.revert()
676 def update_module_dir (self):
677 if self.options.fast_checks:
678 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
680 if self.options.verbose:
681 print 'Updating', self.module_dir
683 if hasattr(self,'branch'):
684 self.repository.update(branch=self.branch)
685 elif hasattr(self,'tagname'):
686 self.repository.update(branch=self.tagname)
688 self.repository.update()
690 def main_specname (self):
691 attempt="%s/%s.spec"%(self.module_dir,self.name)
692 if os.path.isfile (attempt):
694 pattern1="%s/*.spec"%self.module_dir
695 level1=glob(pattern1)
698 pattern2="%s/*/*.spec"%self.module_dir
699 level2=glob(pattern2)
703 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.pathname,pattern1,pattern2)
705 def all_specnames (self):
706 level1=glob("%s/*.spec" % self.module_dir)
707 if level1: return level1
708 level2=glob("%s/*/*.spec" % self.module_dir)
711 def parse_spec (self, specfile, varnames):
712 if self.options.verbose:
713 print 'Parsing',specfile,
719 for line in f.readlines():
720 attempt=Module.matcher_rpm_define.match(line)
722 (define,var,value)=attempt.groups()
726 if self.options.debug:
727 print 'found',len(result),'keys'
728 for (k,v) in result.iteritems():
732 # stores in self.module_name_varname the rpm variable to be used for the module's name
733 # and the list of these names in self.varnames
734 def spec_dict (self):
735 specfile=self.main_specname()
736 redirector_keys = [ varname for (varname,default) in Module.redirectors]
737 redirect_dict = self.parse_spec(specfile,redirector_keys)
738 if self.options.debug:
739 print '1st pass parsing done, redirect_dict=',redirect_dict
741 for (varname,default) in Module.redirectors:
742 if redirect_dict.has_key(varname):
743 setattr(self,varname,redirect_dict[varname])
744 varnames += [redirect_dict[varname]]
746 setattr(self,varname,default)
747 varnames += [ default ]
748 self.varnames = varnames
749 result = self.parse_spec (specfile,self.varnames)
750 if self.options.debug:
751 print '2st pass parsing done, varnames=',varnames,'result=',result
754 def patch_spec_var (self, patch_dict,define_missing=False):
755 for specfile in self.all_specnames():
756 # record the keys that were changed
757 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
758 newspecfile=specfile+".new"
759 if self.options.verbose:
760 print 'Patching',specfile,'for',patch_dict.keys()
762 new=open(newspecfile,"w")
764 for line in spec.readlines():
765 attempt=Module.matcher_rpm_define.match(line)
767 (define,var,value)=attempt.groups()
768 if var in patch_dict.keys():
769 if self.options.debug:
770 print 'rewriting %s as %s'%(var,patch_dict[var])
771 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
776 for (key,was_changed) in changed.iteritems():
778 if self.options.debug:
779 print 'rewriting missing %s as %s'%(key,patch_dict[key])
780 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
783 os.rename(newspecfile,specfile)
785 # returns all lines until the magic line
786 def unignored_lines (self, logfile):
788 white_line_matcher = re.compile("\A\s*\Z")
789 for logline in file(logfile).readlines():
790 if logline.strip() == Module.svn_magic_line:
792 elif white_line_matcher.match(logline):
795 result.append(logline.strip()+'\n')
798 # creates a copy of the input with only the unignored lines
799 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
801 f.write(self.setting_tag_format%new_tag_name + '\n')
802 for line in self.unignored_lines(filein):
806 def insert_changelog (self, logfile, oldtag, newtag):
807 for specfile in self.all_specnames():
808 newspecfile=specfile+".new"
809 if self.options.verbose:
810 print 'Inserting changelog from %s into %s'%(logfile,specfile)
812 new=open(newspecfile,"w")
813 for line in spec.readlines():
815 if re.compile('%changelog').match(line):
816 dateformat="* %a %b %d %Y"
817 datepart=time.strftime(dateformat)
818 logpart="%s <%s> - %s"%(Module.config['username'],
819 Module.config['email'],
821 new.write(datepart+" "+logpart+"\n")
822 for logline in self.unignored_lines(logfile):
823 new.write("- " + logline)
827 os.rename(newspecfile,specfile)
829 def show_dict (self, spec_dict):
830 if self.options.verbose:
831 for (k,v) in spec_dict.iteritems():
834 def last_tag (self, spec_dict):
836 return "%s-%s" % (spec_dict[self.module_version_varname],
837 spec_dict[self.module_taglevel_varname])
839 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
841 def tag_name (self, spec_dict, old_svn_name=False):
842 base_tag_name = self.name
844 base_tag_name = git_to_svn_name(self.name)
845 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
848 ##############################
849 # using fine_grain means replacing only those instances that currently refer to this tag
850 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
851 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
852 newtagsfile=tagsfile+".new"
854 new=open(newtagsfile,"w")
857 # fine-grain : replace those lines that refer to oldname
859 if self.options.verbose:
860 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
861 matcher=re.compile("^(.*)%s(.*)"%oldname)
862 for line in tags.readlines():
863 if not matcher.match(line):
866 (begin,end)=matcher.match(line).groups()
867 new.write(begin+newname+end+"\n")
869 # brute-force : change uncommented lines that define <module>-SVNPATH
871 if self.options.verbose:
872 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.pathname,tagsfile),
873 pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
874 %(self.name,self.name)
875 matcher_module=re.compile(pattern)
876 for line in tags.readlines():
877 attempt=matcher_module.match(line)
879 if line.find("-GITPATH") >= 0:
880 modulepath = "%s-GITPATH"%self.name
881 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.pathname,newname)
883 modulepath = "%s-SVNPATH"%self.name
884 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
885 if self.options.verbose:
886 print ' ' + modulepath,
887 new.write(replacement)
893 os.rename(newtagsfile,tagsfile)
894 if self.options.verbose: print "%d changes"%matches
897 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
898 if self.options.verbose:
899 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
901 found_tagname = tagname
902 found = self.repository.tag_exists(tagname)
903 if not found and old_svn_tag_name:
904 if self.options.verbose:
906 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
907 found = self.repository.tag_exists(old_svn_tag_name)
909 found_tagname = old_svn_tag_name
911 if (found and need_it) or (not found and not need_it):
912 if self.options.verbose:
914 if found: print "- found"
915 else: print "- not found"
917 if self.options.verbose:
920 raise Exception, "tag (%s) is already there" % tagname
922 raise Exception, "can not find required tag (%s)" % tagname
927 ##############################
929 self.init_module_dir()
930 self.revert_module_dir()
931 self.update_module_dir()
933 spec_dict = self.spec_dict()
934 self.show_dict(spec_dict)
937 old_tag_name = self.tag_name(spec_dict)
938 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
940 if (self.options.new_version):
941 # new version set on command line
942 spec_dict[self.module_version_varname] = self.options.new_version
943 spec_dict[self.module_taglevel_varname] = 0
946 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
947 spec_dict[self.module_taglevel_varname] = new_taglevel
949 new_tag_name = self.tag_name(spec_dict)
952 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
953 new_tag_name = self.check_tag(new_tag_name, need_it=False)
956 diff_output = self.repository.diff_with_tag(old_tag_name)
957 if len(diff_output) == 0:
958 if not prompt ("No pending difference in module %s, want to tag anyway"%self.pathname,False):
961 # side effect in trunk's specfile
962 self.patch_spec_var(spec_dict)
964 # prepare changelog file
965 # we use the standard subversion magic string (see svn_magic_line)
966 # so we can provide useful information, such as version numbers and diff
968 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
969 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
970 setting_tag_line=Module.setting_tag_format%new_tag_name
971 file(changelog,"w").write("""
974 Please write a changelog for this new tag in the section above
975 """%(Module.svn_magic_line,setting_tag_line))
977 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
978 file(changelog,"a").write('DIFF=========\n' + diff_output)
980 if self.options.debug:
984 self.run("%s %s"%(self.options.editor,changelog))
985 # strip magic line in second file - looks like svn has changed its magic line with 1.6
986 # so we do the job ourselves
987 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
988 # insert changelog in spec
989 if self.options.changelog:
990 self.insert_changelog (changelog,old_tag_name,new_tag_name)
993 build_path = os.path.join(self.options.workdir,
994 Module.config['build'])
995 build = Repository(build_path, self.options)
996 if self.options.build_branch:
997 build.to_branch(self.options.build_branch)
998 if not build.is_clean():
1001 tagsfiles=glob(build.path+"/*-tags.mk")
1002 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
1003 default_answer = 'y'
1006 for tagsfile in tagsfiles:
1007 status=tagsdict[tagsfile]
1008 basename=os.path.basename(tagsfile)
1009 print ".................... Dealing with %s"%basename
1010 while tagsdict[tagsfile] == 'todo' :
1011 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
1012 [ ('y','es'), ('n', 'ext'), ('f','orce'),
1013 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
1016 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1018 print 'Done with %s'%os.path.basename(tagsfile)
1019 tagsdict[tagsfile]='done'
1021 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1023 print build.diff(f=os.path.basename(tagsfile))
1025 build.revert(f=tagsfile)
1027 self.run("cat %s"%tagsfile)
1030 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1031 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1032 d: show current diff for this tag file
1033 r: revert that tag file
1034 c: cat the current tag file
1035 n: move to next file"""%locals()
1037 if prompt("Want to review changes on tags files",False):
1038 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1043 def diff_all_changes():
1045 print self.repository.diff()
1047 def commit_all_changes(log):
1048 if hasattr(self,'branch'):
1049 self.repository.commit(log, branch=self.branch)
1051 self.repository.commit(log)
1054 self.run_prompt("Review module and build", diff_all_changes)
1055 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1056 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1058 if self.options.debug:
1059 print 'Preserving',changelog,'and stripped',changelog_svn
1061 os.unlink(changelog)
1062 os.unlink(changelog_svn)
1065 ##############################
1066 def do_version (self):
1067 self.init_module_dir()
1068 self.revert_module_dir()
1069 self.update_module_dir()
1070 spec_dict = self.spec_dict()
1071 if self.options.www:
1072 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1073 self.last_tag(spec_dict)))
1074 for varname in self.varnames:
1075 if not spec_dict.has_key(varname):
1076 self.html_print ('Could not find %%define for %s'%varname)
1079 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1080 self.html_print ("%-16s %s"%('url',self.repository.url()))
1081 if self.options.verbose:
1082 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1083 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1084 self.html_print_end()
1087 ##############################
1089 self.init_module_dir()
1090 self.revert_module_dir()
1091 self.update_module_dir()
1092 spec_dict = self.spec_dict()
1093 self.show_dict(spec_dict)
1096 tag_name = self.tag_name(spec_dict)
1097 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1100 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1102 if self.options.verbose:
1103 print 'Getting diff'
1104 diff_output = self.repository.diff_with_tag(tag_name)
1106 if self.options.list:
1110 thename=self.friendly_name()
1112 if self.options.www and diff_output:
1113 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1114 thename,self.last_tag(spec_dict),len(diff_output)))
1116 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1117 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1118 self.html_store_pre (diff_output)
1119 elif not self.options.www:
1120 print 'x'*30,'module',thename
1121 print 'x'*20,'<',tag_name
1122 print 'x'*20,'>',thename
1125 ##############################
1126 # store and restitute html fragments
1128 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1131 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1134 def html_quote (text):
1135 return text.replace('&','&').replace('<','<').replace('>','>')
1137 # only the fake error module has multiple titles
1138 def html_store_title (self, title):
1139 if not hasattr(self,'titles'): self.titles=[]
1140 self.titles.append(title)
1142 def html_store_raw (self, html):
1143 if not hasattr(self,'body'): self.body=''
1146 def html_store_pre (self, text):
1147 if not hasattr(self,'body'): self.body=''
1148 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1150 def html_print (self, txt):
1151 if not self.options.www:
1154 if not hasattr(self,'in_list') or not self.in_list:
1155 self.html_store_raw('<ul>')
1157 self.html_store_raw('<li>'+txt+'</li>')
1159 def html_print_end (self):
1160 if self.options.www:
1161 self.html_store_raw ('</ul>')
1164 def html_dump_header(title):
1165 nowdate=time.strftime("%Y-%m-%d")
1166 nowtime=time.strftime("%H:%M (%Z)")
1167 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1168 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1171 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1172 <style type="text/css">
1173 body { font-family:georgia, serif; }
1174 h1 {font-size: large; }
1175 p.title {font-size: x-large; }
1176 span.error {text-weight:bold; color: red; }
1180 <p class='title'> %s - status on %s at %s</p>
1182 """%(title,title,nowdate,nowtime)
1185 def html_dump_middle():
1189 def html_dump_footer():
1190 print "</body></html"
1192 def html_dump_toc(self):
1193 if hasattr(self,'titles'):
1194 for title in self.titles:
1195 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1197 def html_dump_body(self):
1198 if hasattr(self,'titles'):
1199 for title in self.titles:
1200 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1201 if hasattr(self,'body'):
1203 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1207 class Build(Module):
1209 def __get_modules(self, tagfile):
1210 self.init_module_dir()
1213 tagfile = os.path.join(self.module_dir, tagfile)
1214 for line in open(tagfile):
1216 name, url = line.split(':=')
1217 name, git_or_svn_path = name.rsplit('-', 1)
1218 name = svn_to_git_name(name.strip())
1219 modules[name] = (git_or_svn_path.strip(), url.strip())
1224 def get_modules(self, tagfile):
1225 modules = self.__get_modules(tagfile)
1226 for module in modules:
1227 module_type = tag_or_branch = ""
1229 path_type, url = modules[module]
1230 if path_type == "GITPATH":
1231 module_spec = os.path.split(url)[-1].replace(".git","")
1232 name, tag_or_branch, module_type = self.parse_module_spec(module_spec)
1234 tag_or_branch = os.path.split(url)[-1].strip()
1235 if url.find('/tags/') >= 0:
1237 elif url.find('/branches/') >= 0:
1238 module_type = "branch"
1240 modules[module] = {"module_type" : module_type,
1241 "path_type": path_type,
1242 "tag_or_branch": tag_or_branch,
1248 def modules_diff(first, second):
1251 for module in first:
1252 if module not in second:
1253 print "=== module %s missing in right-hand side ==="%module
1255 if first[module]['tag_or_branch'] != second[module]['tag_or_branch']:
1256 diff[module] = (first[module]['tag_or_branch'], second[module]['tag_or_branch'])
1258 first_set = set(first.keys())
1259 second_set = set(second.keys())
1261 new_modules = list(second_set - first_set)
1262 removed_modules = list(first_set - second_set)
1264 return diff, new_modules, removed_modules
1266 def release_changelog(options, buildtag_old, buildtag_new):
1269 tagfile = options.distrotags[0]
1270 if not tagfile: raise
1272 print "ERROR: provide a tagfile name (eg. onelab, onelab-k27, planetlab)"
1274 tagfile = "%s-tags.mk" % tagfile
1279 print '= build tag %s to %s =' % (buildtag_old, buildtag_new)
1280 print '== distro %s (%s to %s) ==' % (tagfile, buildtag_old, buildtag_new)
1282 build = Build("build@%s" % buildtag_old, options)
1283 build.init_module_dir()
1284 first = build.get_modules(tagfile)
1286 print ' * from', buildtag_old, build.repository.gitweb()
1288 build = Build("build@%s" % buildtag_new, options)
1289 build.init_module_dir()
1290 second = build.get_modules(tagfile)
1292 print ' * to', buildtag_new, build.repository.gitweb()
1294 diff, new_modules, removed_modules = modules_diff(first, second)
1297 def get_module(name, tag):
1298 if not tag or tag == "trunk":
1299 return Module("%s" % (module), options)
1301 return Module("%s@%s" % (module, tag), options)
1305 print '=== %s - %s to %s : package %s ===' % (tagfile, buildtag_old, buildtag_new, module)
1307 first, second = diff[module]
1308 m = get_module(module, first)
1309 os.system('rm -rf %s' % m.module_dir) # cleanup module dir
1312 if m.repository.type == "svn":
1313 print ' * from', first, m.repository.url()
1315 print ' * from', first, m.repository.gitweb()
1317 specfile = m.main_specname()
1318 (tmpfd, tmpfile) = tempfile.mkstemp()
1319 os.system("cp -f /%s %s" % (specfile, tmpfile))
1321 m = get_module(module, second)
1323 specfile = m.main_specname()
1325 if m.repository.type == "svn":
1326 print ' * to', second, m.repository.url()
1328 print ' * to', second, m.repository.gitweb()
1331 os.system("diff -u %s %s" % (tmpfile, specfile))
1336 for module in new_modules:
1337 print '=== %s : new package in build %s ===' % (tagfile, module)
1339 for module in removed_modules:
1340 print '=== %s : removed package from build %s ===' % (tagfile, module)
1343 def adopt_tag (options, args):
1345 for module in options.modules:
1346 modules += module.split()
1347 for module in modules:
1348 modobj=Module(module,options)
1349 for tags_file in args:
1351 print 'adopting tag %s for %s in %s'%(options.tag,module,tags_file)
1352 modobj.patch_tags_file(tags_file,'_unused_',options.tag,fine_grain=False)
1354 Command("git diff %s"%" ".join(args),options).run()
1356 ##############################
1359 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1361 module-tools : a set of tools to manage subversion tags and specfile
1362 requires the specfile to either
1363 * define *version* and *taglevel*
1365 * define redirection variables module_version_varname / module_taglevel_varname
1367 by default, the trunk of modules is taken into account
1368 in this case, just mention the module name as <module_desc>
1370 if you wish to work on a branch rather than on the trunk,
1371 you can use something like e.g. Mom:2.1 as <module_desc>
1373 release_usage="""Usage: %prog [options] tag1 .. tagn
1374 Extract release notes from the changes in specfiles between several build tags, latest first
1376 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1377 You can refer to a (build) branch by prepending a colon, like in
1378 release-changelog :4.2 4.2-rc25
1379 You can refer to the build trunk by just mentioning 'trunk', e.g.
1380 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1382 adopt_usage="""Usage: %prog [options] tag-file[s]
1383 With this command you can adopt a specifi tag or branch in your tag files
1384 This should be run in your daily build workdir; no call of git nor svn is done
1386 adopt-tag -m "plewww plcapi" -m Monitor onelab*tags.mk
1387 adopt-tag -m sfa -t sfa-1.0-33 *tags.mk
1389 common_usage="""More help:
1390 see http://svn.planet-lab.org/wiki/ModuleTools"""
1393 'list' : "displays a list of available tags or branches",
1394 'version' : "check latest specfile and print out details",
1395 'diff' : "show difference between module (trunk or branch) and latest tag",
1396 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1397 create new tag and and monitor its adoption in build/*-tags.mk""",
1398 'branch' : """create a branch for this module, from the latest tag on the trunk,
1399 and change trunk's version number to reflect the new branch name;
1400 you can specify the new branch name by using module:branch""",
1401 'sync' : """create a tag from the module
1402 this is a last resort option, mostly for repairs""",
1403 'changelog' : """extract changelog between build tags
1404 expected arguments are a list of tags""",
1405 'adopt' : """locally adopt a specific tag""",
1408 silent_modes = ['list']
1409 # 'changelog' is for release-changelog
1410 # 'adopt' is for 'adopt-tag'
1411 regular_modes = set(modes.keys()).difference(set(['changelog','adopt']))
1414 def optparse_list (option, opt, value, parser):
1416 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1418 setattr(parser.values,option.dest,value.split())
1423 # hack - need to check for adopt first as 'adopt-tag' contains tag..
1424 for function in [ 'adopt' ] + Main.modes.keys():
1425 if sys.argv[0].find(function) >= 0:
1429 print "Unsupported command",sys.argv[0]
1430 print "Supported commands:" + " ".join(Main.modes.keys())
1433 usage='undefined usage, mode=%s'%mode
1434 if mode in Main.regular_modes:
1435 usage = Main.module_usage
1436 usage += Main.common_usage
1437 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1438 elif mode=='changelog':
1439 usage = Main.release_usage
1440 usage += Main.common_usage
1442 usage = Main.adopt_usage
1443 usage += Main.common_usage
1445 parser=OptionParser(usage=usage)
1447 # the 'adopt' mode is really special and doesn't share any option
1449 parser.add_option("-m","--module",action="append",dest="modules",default=[],
1450 help="modules, can be used several times or with quotes")
1451 parser.add_option("-t","--tag",action="store", dest="tag", default='master',
1452 help="specify the tag to adopt, default is 'master'")
1453 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1454 help="run in verbose mode")
1455 (options, args) = parser.parse_args()
1456 options.workdir='unused'
1457 options.dry_run=False
1458 options.mode='adopt'
1459 if len(args)==0 or len(options.modules)==0:
1462 adopt_tag (options,args)
1465 # the other commands (module-* and release-changelog) share the same skeleton
1466 if mode == "tag" or mode == 'branch':
1467 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1468 help="set new version and reset taglevel to 0")
1470 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1471 help="do not update changelog section in specfile when tagging")
1472 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1473 help="specify a build branch; used for locating the *tags.mk files where adoption is to take place")
1474 if mode == "tag" or mode == "sync" :
1475 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1476 help="specify editor")
1478 if mode in ["diff","version"] :
1479 parser.add_option("-W","--www", action="store", dest="www", default=False,
1480 help="export diff in html format, e.g. -W trunk")
1483 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1484 help="just list modules that exhibit differences")
1486 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1487 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1488 help="run on all modules as found in %s"%default_modules_list)
1489 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1490 help="run on all modules found in specified file")
1491 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1492 help="dry run - shell commands are only displayed")
1493 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1494 default=[], nargs=1,type="string",
1495 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1496 -- can be set multiple times, or use quotes""")
1498 parser.add_option("-w","--workdir", action="store", dest="workdir",
1499 default="%s/%s"%(os.getenv("HOME"),"modules"),
1500 help="""name for dedicated working dir - defaults to ~/modules
1501 ** THIS MUST NOT ** be your usual working directory""")
1502 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1503 help="skip safety checks, such as svn updates -- use with care")
1504 parser.add_option("-B","--build-module",action="store",dest="build_module",default=None,
1505 help="specify a build module to owerride the one in the CONFIG")
1507 # default verbosity depending on function - temp
1508 verbose_modes= ['tag', 'sync', 'branch']
1510 if mode not in verbose_modes:
1511 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1512 help="run in verbose mode")
1514 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1515 help="run in quiet (non-verbose) mode")
1516 (options, args) = parser.parse_args()
1518 if not hasattr(options,'dry_run'):
1519 options.dry_run=False
1520 if not hasattr(options,'www'):
1528 if options.all_modules:
1529 options.modules_list=default_modules_list
1530 if options.modules_list:
1531 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1535 Module.init_homedir(options)
1538 if mode in Main.regular_modes:
1539 modules=[ Module(modname,options) for modname in args ]
1540 # hack: create a dummy Module to store errors/warnings
1541 error_module = Module('__errors__',options)
1543 for module in modules:
1544 if len(args)>1 and mode not in Main.silent_modes:
1546 print '========================================',module.friendly_name()
1547 # call the method called do_<mode>
1548 method=Module.__dict__["do_%s"%mode]
1553 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1554 (module.friendly_name(), str(e))
1555 error_module.html_store_title(title)
1558 traceback.print_exc()
1559 print 'Skipping module %s: '%modname,e
1563 modetitle="Changes to tag in %s"%options.www
1564 elif mode == "version":
1565 modetitle="Latest tags in %s"%options.www
1566 modules.append(error_module)
1567 error_module.html_dump_header(modetitle)
1568 for module in modules:
1569 module.html_dump_toc()
1570 Module.html_dump_middle()
1571 for module in modules:
1572 module.html_dump_body()
1573 Module.html_dump_footer()
1575 # if we provide, say a b c d, we want to build (a,b) (b,c) and (c,d)
1576 for (f,t) in zip ( args[:-1], args [1:]):
1577 release_changelog(options, f,t)
1580 ####################
1581 if __name__ == "__main__" :
1584 except KeyboardInterrupt: