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",
27 #we keep planetlab modules in a sub-directory
28 "planetlab/PLEWWW": "planetlab/plewww",
29 "planetlab/PLCAPI": "planetlab/plcapi",
30 "planetlab/BootManager": "planetlab/bootmanager",
31 "planetlab/BootCD": "planetlab/bootcd",
32 "planetlab/VserverReference": "planetlab/vserver-reference",
33 "planetlab/BootstrapFS": "planetlab/bootstrapfs",
34 "planetlab/MyPLC": "planetlab/myplc",
35 "planetlab/CoDemux": "planetlab/codemux",
36 "planetlab/NodeManager": "planetlab/nodemanager",
37 "planetlab/NodeUpdate": "planetlab/nodeupdate"
41 def svn_to_git_name(module):
42 if RENAMED_SVN_MODULES.has_key(module):
43 return RENAMED_SVN_MODULES[module]
46 def git_to_svn_name(module):
47 for key in RENAMED_SVN_MODULES:
48 if module == RENAMED_SVN_MODULES[key]:
53 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
54 def prompt (question,default=True,other_choices=[],allow_outside=False):
55 if not isinstance (other_choices,list):
56 other_choices = [ other_choices ]
57 chars = [ c for (c,rest) in other_choices ]
61 if default is True: choices.append('[y]')
62 else : choices.append('y')
64 if default is False: choices.append('[n]')
65 else : choices.append('n')
67 for (char,choice) in other_choices:
69 choices.append("["+char+"]"+choice)
71 choices.append("<"+char+">"+choice)
73 answer=raw_input(question + " " + "/".join(choices) + " ? ")
76 answer=answer[0].lower()
78 if 'y' in chars: return 'y'
81 if 'n' in chars: return 'n'
84 for (char,choice) in other_choices:
89 return prompt(question,default,other_choices)
95 editor = os.environ['EDITOR']
103 def print_fold (line):
104 while len(line) >= fold_length:
105 print line[:fold_length],'\\'
106 line=line[fold_length:]
110 def __init__ (self,command,options):
113 self.tmp="/tmp/command-%d"%os.getpid()
116 if self.options.dry_run:
117 print 'dry_run',self.command
119 if self.options.verbose and self.options.mode not in Main.silent_modes:
120 print '+',self.command
122 return os.system(self.command)
124 def run_silent (self):
125 if self.options.dry_run:
126 print 'dry_run',self.command
128 if self.options.verbose:
129 print '+',self.command,' .. ',
131 retcod=os.system(self.command + " &> " + self.tmp)
133 print "FAILED ! -- out+err below (command was %s)"%self.command
134 os.system("cat " + self.tmp)
135 print "FAILED ! -- end of quoted output"
136 elif self.options.verbose:
142 if self.run_silent() !=0:
143 raise Exception,"Command %s failed"%self.command
145 # returns stdout, like bash's $(mycommand)
146 def output_of (self,with_stderr=False):
147 if self.options.dry_run:
148 print 'dry_run',self.command
149 return 'dry_run output'
150 tmp="/tmp/status-%d"%os.getpid()
151 if self.options.debug:
152 print '+',self.command,' .. ',
161 result=file(tmp).read()
163 if self.options.debug:
171 def __init__(self, path, options):
173 self.options = options
176 return os.path.basename(self.path)
179 out = Command("svn info %s" % self.path, self.options).output_of()
180 for line in out.split('\n'):
181 if line.startswith("URL:"):
182 return line.split()[1].strip()
185 out = Command("svn info %s" % self.path, self.options).output_of()
186 for line in out.split('\n'):
187 if line.startswith("Repository Root:"):
188 root = line.split()[2].strip()
189 return "%s/%s" % (root, self.pathname())
192 def checkout(cls, remote, local, options, recursive=False):
194 svncommand = "svn co %s %s" % (remote, local)
196 svncommand = "svn co -N %s %s" % (remote, local)
197 Command("rm -rf %s" % local, options).run_silent()
198 Command(svncommand, options).run_fatal()
200 return SvnRepository(local, options)
203 def remote_exists(cls, remote):
204 return os.system("svn list %s &> /dev/null" % remote) == 0
206 def tag_exists(self, tagname):
207 url = "%s/tags/%s" % (self.repo_root(), tagname)
208 return SvnRepository.remote_exists(url)
210 def update(self, subdir="", recursive=True, branch=None):
211 path = os.path.join(self.path, subdir)
213 svncommand = "svn up %s" % path
215 svncommand = "svn up -N %s" % path
216 Command(svncommand, self.options).run_fatal()
218 def commit(self, logfile):
219 # add all new files to the repository
220 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
221 self.path, self.options).output_of()
222 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
224 def to_branch(self, branch):
225 remote = "%s/branches/%s" % (self.repo_root(), branch)
226 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
228 def to_tag(self, tag):
229 remote = "%s/tags/%s" % (self.repo_root(), branch)
230 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
232 def tag(self, tagname, logfile):
233 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
234 self_url = self.url()
235 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
237 def diff(self, f=""):
239 f = os.path.join(self.path, f)
242 return Command("svn diff %s" % f, self.options).output_of(True)
244 def diff_with_tag(self, tagname):
245 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
246 return Command("svn diff %s %s" % (tag_url, self.url()),
247 self.options).output_of(True)
249 def revert(self, f=""):
251 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
254 Command("svn revert %s -R" % self.path, self.options).run_fatal()
255 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
256 self.path, self.options).run_silent()
259 command="svn status %s" % self.path
260 return len(Command(command,self.options).output_of(True)) == 0
263 return os.path.exists(os.path.join(self.path, ".svn"))
269 def __init__(self, path, options):
271 self.options = options
274 return os.path.basename(self.path)
277 return self.repo_root()
280 c = Command("git show | grep commit | awk '{print $2;}'", self.options)
281 out = self.__run_in_repo(c.output_of).strip()
282 return "http://git.onelab.eu/?p=%s.git;a=commit;h=%s" % (self.pathname(), out)
285 c = Command("git remote show origin", self.options)
286 out = self.__run_in_repo(c.output_of)
287 for line in out.split('\n'):
288 if line.strip().startswith("Fetch URL:"):
289 return line.split()[2]
292 def checkout(cls, remote, local, options, depth=0):
293 Command("rm -rf %s" % local, options).run_silent()
294 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
295 return GitRepository(local, options)
298 def remote_exists(cls, remote):
299 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
301 def tag_exists(self, tagname):
302 command = 'git tag -l | grep "^%s$"' % tagname
303 c = Command(command, self.options)
304 out = self.__run_in_repo(c.output_of, with_stderr=True)
307 def __run_in_repo(self, fun, *args, **kwargs):
310 ret = fun(*args, **kwargs)
314 def __run_command_in_repo(self, command, ignore_errors=False):
315 c = Command(command, self.options)
317 return self.__run_in_repo(c.output_of)
319 return self.__run_in_repo(c.run_fatal)
321 def __is_commit_id(self, id):
322 c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
323 ret = self.__run_in_repo(c.output_of, with_stderr=False)
324 if ret.strip() == id:
328 def update(self, subdir=None, recursive=None, branch="master"):
329 if branch == "master":
330 self.__run_command_in_repo("git checkout %s" % branch)
332 self.to_branch(branch, remote=True)
333 self.__run_command_in_repo("git fetch origin --tags")
334 self.__run_command_in_repo("git fetch origin")
335 if not self.__is_commit_id(branch):
336 # we don't need to merge anythign for commit ids.
337 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
339 def to_branch(self, branch, remote=True):
342 command = "git branch --track %s origin/%s" % (branch, branch)
343 c = Command(command, self.options)
344 self.__run_in_repo(c.output_of, with_stderr=True)
345 return self.__run_command_in_repo("git checkout %s" % branch)
347 def to_tag(self, tag):
349 return self.__run_command_in_repo("git checkout %s" % tag)
351 def tag(self, tagname, logfile):
352 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
355 def diff(self, f=""):
356 c = Command("git diff %s" % f, self.options)
357 return self.__run_in_repo(c.output_of, with_stderr=True)
359 def diff_with_tag(self, tagname):
360 c = Command("git diff %s" % tagname, self.options)
361 return self.__run_in_repo(c.output_of, with_stderr=True)
363 def commit(self, logfile, branch="master"):
364 self.__run_command_in_repo("git add .", ignore_errors=True)
365 self.__run_command_in_repo("git add -u", ignore_errors=True)
366 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
367 if branch == "master" or self.__is_commit_id(branch):
368 self.__run_command_in_repo("git push")
370 self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
371 self.__run_command_in_repo("git push --tags")
373 def revert(self, f=""):
375 self.__run_command_in_repo("git checkout %s" % f)
378 self.__run_command_in_repo("git --no-pager reset --hard")
379 self.__run_command_in_repo("git --no-pager clean -f")
384 s="nothing to commit (working directory clean)"
385 return Command(command, self.options).output_of(True).find(s) >= 0
386 return self.__run_in_repo(check_commit)
389 return os.path.exists(os.path.join(self.path, ".git"))
393 """ Generic repository """
394 supported_repo_types = [SvnRepository, GitRepository]
396 def __init__(self, path, options):
398 self.options = options
399 for repo in self.supported_repo_types:
400 self.repo = repo(self.path, self.options)
401 if self.repo.is_valid():
405 def has_moved_to_git(cls, module, config):
406 module = svn_to_git_name(module)
407 # check if the module is already in Git
408 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
409 return GitRepository.remote_exists(Module.git_remote_dir(module))
413 def remote_exists(cls, remote):
414 for repo in Repository.supported_repo_types:
415 if repo.remote_exists(remote):
419 def __getattr__(self, attr):
420 return getattr(self.repo, attr)
424 # support for tagged module is minimal, and is for the Build class only
427 svn_magic_line="--This line, and those below, will be ignored--"
428 setting_tag_format = "Setting tag %s"
430 redirectors=[ # ('module_name_varname','name'),
431 ('module_version_varname','version'),
432 ('module_taglevel_varname','taglevel'), ]
434 # where to store user's config
435 config_storage="CONFIG"
440 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
441 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
442 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
443 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
444 ("build", "Enter the name of your build module","build"),
445 ('username',"Enter your firstname and lastname for changelogs",""),
446 ("email","Enter your email address for changelogs",""),
450 def prompt_config_option(cls, key, message, default):
451 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
454 def prompt_config (cls):
455 for (key,message,default) in cls.configKeys:
457 while not cls.config[key]:
458 cls.prompt_config_option(key, message, default)
460 # for parsing module spec name:branch
461 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-\/]+):(?P<branch>[\w\.-]+)\Z")
462 # special form for tagged module - for Build
463 matcher_tag_spec=re.compile("\A(?P<name>[\w\.-\/]+)@(?P<tagname>[\w\.-]+)\Z")
465 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
468 def parse_module_spec(cls, module_spec):
469 name = branch_or_tagname = module_type = ""
471 attempt=Module.matcher_branch_spec.match(module_spec)
473 module_type = "branch"
474 name=attempt.group('name')
475 branch_or_tagname=attempt.group('branch')
477 attempt=Module.matcher_tag_spec.match(module_spec)
480 name=attempt.group('name')
481 branch_or_tagname=attempt.group('tagname')
484 return name, branch_or_tagname, module_type
487 def __init__ (self,module_spec,options):
489 self.pathname, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
490 self.name = os.path.basename(self.pathname)
492 if module_type == "branch":
493 self.branch=branch_or_tagname
494 elif module_type == "tag":
495 self.tagname=branch_or_tagname
497 # when available prefer to use git module name internally
498 self.name = svn_to_git_name(self.name)
501 self.module_dir="%s/%s"%(options.workdir,self.pathname)
502 self.repository = None
505 def run (self,command):
506 return Command(command,self.options).run()
507 def run_fatal (self,command):
508 return Command(command,self.options).run_fatal()
509 def run_prompt (self,message,fun, *args):
510 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
511 if not self.options.verbose:
513 choice=prompt(message,True,('s','how'))
517 elif choice is False:
518 print 'About to run function:', fun_msg
520 question=message+" - want to run function: " + fun_msg
521 if prompt(question,True):
524 def friendly_name (self):
525 if hasattr(self,'branch'):
526 return "%s:%s"%(self.pathname,self.branch)
527 elif hasattr(self,'tagname'):
528 return "%s@%s"%(self.pathname,self.tagname)
533 def git_remote_dir (cls, name):
534 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
537 def svn_remote_dir (cls, name):
538 name = git_to_svn_name(name)
539 svn = cls.config['svnpath']
540 if svn.endswith('/'):
541 return "%s%s" % (svn, name)
542 return "%s/%s" % (svn, name)
544 def svn_selected_remote(self):
545 svn_name = git_to_svn_name(self.name)
546 remote = self.svn_remote_dir(svn_name)
547 if hasattr(self,'branch'):
548 remote = "%s/branches/%s" % (remote, self.branch)
549 elif hasattr(self,'tagname'):
550 remote = "%s/tags/%s" % (remote, self.tagname)
552 remote = "%s/trunk" % remote
557 def init_homedir (cls, options):
558 if options.verbose and options.mode not in Main.silent_modes:
559 print 'Checking for', options.workdir
560 storage="%s/%s"%(options.workdir, cls.config_storage)
561 # sanity check. Either the topdir exists AND we have a config/storage
562 # or topdir does not exist and we create it
563 # to avoid people use their own daily svn repo
564 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
565 print """The directory %s exists and has no CONFIG file
566 If this is your regular working directory, please provide another one as the
567 module-* commands need a fresh working dir. Make sure that you do not use
568 that for other purposes than tagging""" % options.workdir
571 def checkout_build():
572 print "Checking out build module..."
573 remote = cls.git_remote_dir(cls.config['build'])
574 local = os.path.join(options.workdir, cls.config['build'])
575 GitRepository.checkout(remote, local, options, depth=1)
580 for (key,message,default) in Module.configKeys:
581 f.write("%s=%s\n"%(key,Module.config[key]))
584 print 'Stored',storage
585 Command("cat %s"%storage,options).run()
590 for line in f.readlines():
591 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
592 Module.config[key]=value
595 # owerride config variables using options.
596 if options.build_module:
597 Module.config['build'] = options.build_module
599 if not os.path.isdir (options.workdir):
600 print "Cannot find",options.workdir,"let's create it"
601 Command("mkdir -p %s" % options.workdir, options).run_silent()
607 # check missing config options
609 for (key,message,default) in cls.configKeys:
610 if not Module.config.has_key(key):
611 print "Configuration changed for module-tools"
612 cls.prompt_config_option(key, message, default)
616 Command("rm -rf %s" % options.workdir, options).run_silent()
617 Command("mkdir -p %s" % options.workdir, options).run_silent()
621 build_dir = os.path.join(options.workdir, cls.config['build'])
622 if not os.path.isdir(build_dir):
625 build = Repository(build_dir, options)
626 if not build.is_clean():
627 print "build module needs a revert"
632 if options.verbose and options.mode not in Main.silent_modes:
633 print '******** Using config'
634 for (key,message,default) in Module.configKeys:
635 print '\t',key,'=',Module.config[key]
637 def init_module_dir (self):
638 if self.options.verbose:
639 print 'Checking for',self.module_dir
641 if not os.path.isdir (self.module_dir):
642 if Repository.has_moved_to_git(self.pathname, Module.config):
643 self.repository = GitRepository.checkout(self.git_remote_dir(self.pathname),
647 remote = self.svn_selected_remote()
648 self.repository = SvnRepository.checkout(remote,
650 self.options, recursive=False)
652 self.repository = Repository(self.module_dir, self.options)
653 if self.repository.type == "svn":
654 # check if module has moved to git
655 if Repository.has_moved_to_git(self.pathname, Module.config):
656 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
657 self.init_module_dir()
658 # check if we have the required branch/tag
659 if self.repository.url() != self.svn_selected_remote():
660 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
661 self.init_module_dir()
663 elif self.repository.type == "git":
664 if hasattr(self,'branch'):
665 self.repository.to_branch(self.branch)
666 elif hasattr(self,'tagname'):
667 self.repository.to_tag(self.tagname)
670 raise Exception, 'Cannot find %s - check module name'%self.module_dir
673 def revert_module_dir (self):
674 if self.options.fast_checks:
675 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
677 if self.options.verbose:
678 print 'Checking whether', self.module_dir, 'needs being reverted'
680 if not self.repository.is_clean():
681 self.repository.revert()
683 def update_module_dir (self):
684 if self.options.fast_checks:
685 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
687 if self.options.verbose:
688 print 'Updating', self.module_dir
690 if hasattr(self,'branch'):
691 self.repository.update(branch=self.branch)
692 elif hasattr(self,'tagname'):
693 self.repository.update(branch=self.tagname)
695 self.repository.update()
697 def main_specname (self):
698 attempt="%s/%s.spec"%(self.module_dir,self.name)
699 if os.path.isfile (attempt):
701 pattern1="%s/*.spec"%self.module_dir
702 level1=glob(pattern1)
705 pattern2="%s/*/*.spec"%self.module_dir
706 level2=glob(pattern2)
710 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.pathname,pattern1,pattern2)
712 def all_specnames (self):
713 level1=glob("%s/*.spec" % self.module_dir)
714 if level1: return level1
715 level2=glob("%s/*/*.spec" % self.module_dir)
718 def parse_spec (self, specfile, varnames):
719 if self.options.verbose:
720 print 'Parsing',specfile,
726 for line in f.readlines():
727 attempt=Module.matcher_rpm_define.match(line)
729 (define,var,value)=attempt.groups()
733 if self.options.debug:
734 print 'found',len(result),'keys'
735 for (k,v) in result.iteritems():
739 # stores in self.module_name_varname the rpm variable to be used for the module's name
740 # and the list of these names in self.varnames
741 def spec_dict (self):
742 specfile=self.main_specname()
743 redirector_keys = [ varname for (varname,default) in Module.redirectors]
744 redirect_dict = self.parse_spec(specfile,redirector_keys)
745 if self.options.debug:
746 print '1st pass parsing done, redirect_dict=',redirect_dict
748 for (varname,default) in Module.redirectors:
749 if redirect_dict.has_key(varname):
750 setattr(self,varname,redirect_dict[varname])
751 varnames += [redirect_dict[varname]]
753 setattr(self,varname,default)
754 varnames += [ default ]
755 self.varnames = varnames
756 result = self.parse_spec (specfile,self.varnames)
757 if self.options.debug:
758 print '2st pass parsing done, varnames=',varnames,'result=',result
761 def patch_spec_var (self, patch_dict,define_missing=False):
762 for specfile in self.all_specnames():
763 # record the keys that were changed
764 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
765 newspecfile=specfile+".new"
766 if self.options.verbose:
767 print 'Patching',specfile,'for',patch_dict.keys()
769 new=open(newspecfile,"w")
771 for line in spec.readlines():
772 attempt=Module.matcher_rpm_define.match(line)
774 (define,var,value)=attempt.groups()
775 if var in patch_dict.keys():
776 if self.options.debug:
777 print 'rewriting %s as %s'%(var,patch_dict[var])
778 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
783 for (key,was_changed) in changed.iteritems():
785 if self.options.debug:
786 print 'rewriting missing %s as %s'%(key,patch_dict[key])
787 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
790 os.rename(newspecfile,specfile)
792 # returns all lines until the magic line
793 def unignored_lines (self, logfile):
795 white_line_matcher = re.compile("\A\s*\Z")
796 for logline in file(logfile).readlines():
797 if logline.strip() == Module.svn_magic_line:
799 elif white_line_matcher.match(logline):
802 result.append(logline.strip()+'\n')
805 # creates a copy of the input with only the unignored lines
806 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
808 f.write(self.setting_tag_format%new_tag_name + '\n')
809 for line in self.unignored_lines(filein):
813 def insert_changelog (self, logfile, oldtag, newtag):
814 for specfile in self.all_specnames():
815 newspecfile=specfile+".new"
816 if self.options.verbose:
817 print 'Inserting changelog from %s into %s'%(logfile,specfile)
819 new=open(newspecfile,"w")
820 for line in spec.readlines():
822 if re.compile('%changelog').match(line):
823 dateformat="* %a %b %d %Y"
824 datepart=time.strftime(dateformat)
825 logpart="%s <%s> - %s"%(Module.config['username'],
826 Module.config['email'],
828 new.write(datepart+" "+logpart+"\n")
829 for logline in self.unignored_lines(logfile):
830 new.write("- " + logline)
834 os.rename(newspecfile,specfile)
836 def show_dict (self, spec_dict):
837 if self.options.verbose:
838 for (k,v) in spec_dict.iteritems():
841 def last_tag (self, spec_dict):
843 return "%s-%s" % (spec_dict[self.module_version_varname],
844 spec_dict[self.module_taglevel_varname])
846 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
848 def tag_name (self, spec_dict, old_svn_name=False):
849 base_tag_name = self.name
851 base_tag_name = git_to_svn_name(self.name)
852 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
855 ##############################
856 # using fine_grain means replacing only those instances that currently refer to this tag
857 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
858 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
859 newtagsfile=tagsfile+".new"
861 new=open(newtagsfile,"w")
864 # fine-grain : replace those lines that refer to oldname
866 if self.options.verbose:
867 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
868 matcher=re.compile("^(.*)%s(.*)"%oldname)
869 for line in tags.readlines():
870 if not matcher.match(line):
873 (begin,end)=matcher.match(line).groups()
874 new.write(begin+newname+end+"\n")
876 # brute-force : change uncommented lines that define <module>-SVNPATH
878 if self.options.verbose:
879 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.pathname,tagsfile),
880 pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
881 %(self.name,self.name)
882 matcher_module=re.compile(pattern)
883 for line in tags.readlines():
884 attempt=matcher_module.match(line)
886 if line.find("-GITPATH") >= 0:
887 modulepath = "%s-GITPATH"%self.name
888 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.pathname,newname)
890 modulepath = "%s-SVNPATH"%self.name
891 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
892 if self.options.verbose:
893 print ' ' + modulepath,
894 new.write(replacement)
900 os.rename(newtagsfile,tagsfile)
901 if self.options.verbose: print "%d changes"%matches
904 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
905 if self.options.verbose:
906 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
908 found_tagname = tagname
909 found = self.repository.tag_exists(tagname)
910 if not found and old_svn_tag_name:
911 if self.options.verbose:
913 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
914 found = self.repository.tag_exists(old_svn_tag_name)
916 found_tagname = old_svn_tag_name
918 if (found and need_it) or (not found and not need_it):
919 if self.options.verbose:
921 if found: print "- found"
922 else: print "- not found"
924 if self.options.verbose:
927 raise Exception, "tag (%s) is already there" % tagname
929 raise Exception, "can not find required tag (%s)" % tagname
934 ##############################
936 self.init_module_dir()
937 self.revert_module_dir()
938 self.update_module_dir()
940 spec_dict = self.spec_dict()
941 self.show_dict(spec_dict)
944 old_tag_name = self.tag_name(spec_dict)
945 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
947 if (self.options.new_version):
948 # new version set on command line
949 spec_dict[self.module_version_varname] = self.options.new_version
950 spec_dict[self.module_taglevel_varname] = 0
953 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
954 spec_dict[self.module_taglevel_varname] = new_taglevel
956 new_tag_name = self.tag_name(spec_dict)
959 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
960 new_tag_name = self.check_tag(new_tag_name, need_it=False)
963 diff_output = self.repository.diff_with_tag(old_tag_name)
964 if len(diff_output) == 0:
965 if not prompt ("No pending difference in module %s, want to tag anyway"%self.pathname,False):
968 # side effect in trunk's specfile
969 self.patch_spec_var(spec_dict)
971 # prepare changelog file
972 # we use the standard subversion magic string (see svn_magic_line)
973 # so we can provide useful information, such as version numbers and diff
975 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
976 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
977 setting_tag_line=Module.setting_tag_format%new_tag_name
978 file(changelog,"w").write("""
981 Please write a changelog for this new tag in the section above
982 """%(Module.svn_magic_line,setting_tag_line))
984 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
985 file(changelog,"a").write('DIFF=========\n' + diff_output)
987 if self.options.debug:
991 self.run("%s %s"%(self.options.editor,changelog))
992 # strip magic line in second file - looks like svn has changed its magic line with 1.6
993 # so we do the job ourselves
994 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
995 # insert changelog in spec
996 if self.options.changelog:
997 self.insert_changelog (changelog,old_tag_name,new_tag_name)
1000 build_path = os.path.join(self.options.workdir,
1001 Module.config['build'])
1002 build = Repository(build_path, self.options)
1003 if self.options.build_branch:
1004 build.to_branch(self.options.build_branch)
1005 if not build.is_clean():
1008 tagsfiles=glob(build.path+"/*-tags*.mk")
1009 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
1010 default_answer = 'y'
1013 for tagsfile in tagsfiles:
1014 status=tagsdict[tagsfile]
1015 basename=os.path.basename(tagsfile)
1016 print ".................... Dealing with %s"%basename
1017 while tagsdict[tagsfile] == 'todo' :
1018 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
1019 [ ('y','es'), ('n', 'ext'), ('f','orce'),
1020 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
1023 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1025 print 'Done with %s'%os.path.basename(tagsfile)
1026 tagsdict[tagsfile]='done'
1028 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1030 print build.diff(f=os.path.basename(tagsfile))
1032 build.revert(f=tagsfile)
1034 self.run("cat %s"%tagsfile)
1037 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1038 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1039 d: show current diff for this tag file
1040 r: revert that tag file
1041 c: cat the current tag file
1042 n: move to next file"""%locals()
1044 if prompt("Want to review changes on tags files",False):
1045 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1050 def diff_all_changes():
1052 print self.repository.diff()
1054 def commit_all_changes(log):
1055 if hasattr(self,'branch'):
1056 self.repository.commit(log, branch=self.branch)
1058 self.repository.commit(log)
1061 self.run_prompt("Review module and build", diff_all_changes)
1062 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1063 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1065 if self.options.debug:
1066 print 'Preserving',changelog,'and stripped',changelog_svn
1068 os.unlink(changelog)
1069 os.unlink(changelog_svn)
1072 ##############################
1073 def do_version (self):
1074 self.init_module_dir()
1075 self.revert_module_dir()
1076 self.update_module_dir()
1077 spec_dict = self.spec_dict()
1078 if self.options.www:
1079 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1080 self.last_tag(spec_dict)))
1081 for varname in self.varnames:
1082 if not spec_dict.has_key(varname):
1083 self.html_print ('Could not find %%define for %s'%varname)
1086 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1087 self.html_print ("%-16s %s"%('url',self.repository.url()))
1088 if self.options.verbose:
1089 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1090 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1091 self.html_print_end()
1094 ##############################
1096 self.init_module_dir()
1097 self.revert_module_dir()
1098 self.update_module_dir()
1099 spec_dict = self.spec_dict()
1100 self.show_dict(spec_dict)
1103 tag_name = self.tag_name(spec_dict)
1104 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1107 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1109 if self.options.verbose:
1110 print 'Getting diff'
1111 diff_output = self.repository.diff_with_tag(tag_name)
1113 if self.options.list:
1117 thename=self.friendly_name()
1119 if self.options.www and diff_output:
1120 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1121 thename,self.last_tag(spec_dict),len(diff_output)))
1123 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1124 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1125 self.html_store_pre (diff_output)
1126 elif not self.options.www:
1127 print 'x'*30,'module',thename
1128 print 'x'*20,'<',tag_name
1129 print 'x'*20,'>',thename
1132 ##############################
1133 # store and restitute html fragments
1135 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1138 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1141 def html_quote (text):
1142 return text.replace('&','&').replace('<','<').replace('>','>')
1144 # only the fake error module has multiple titles
1145 def html_store_title (self, title):
1146 if not hasattr(self,'titles'): self.titles=[]
1147 self.titles.append(title)
1149 def html_store_raw (self, html):
1150 if not hasattr(self,'body'): self.body=''
1153 def html_store_pre (self, text):
1154 if not hasattr(self,'body'): self.body=''
1155 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1157 def html_print (self, txt):
1158 if not self.options.www:
1161 if not hasattr(self,'in_list') or not self.in_list:
1162 self.html_store_raw('<ul>')
1164 self.html_store_raw('<li>'+txt+'</li>')
1166 def html_print_end (self):
1167 if self.options.www:
1168 self.html_store_raw ('</ul>')
1171 def html_dump_header(title):
1172 nowdate=time.strftime("%Y-%m-%d")
1173 nowtime=time.strftime("%H:%M (%Z)")
1174 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1175 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1178 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1179 <style type="text/css">
1180 body { font-family:georgia, serif; }
1181 h1 {font-size: large; }
1182 p.title {font-size: x-large; }
1183 span.error {text-weight:bold; color: red; }
1187 <p class='title'> %s - status on %s at %s</p>
1189 """%(title,title,nowdate,nowtime)
1192 def html_dump_middle():
1196 def html_dump_footer():
1197 print "</body></html"
1199 def html_dump_toc(self):
1200 if hasattr(self,'titles'):
1201 for title in self.titles:
1202 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1204 def html_dump_body(self):
1205 if hasattr(self,'titles'):
1206 for title in self.titles:
1207 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1208 if hasattr(self,'body'):
1210 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1214 class Build(Module):
1216 def __get_modules(self, tagfile):
1217 self.init_module_dir()
1220 tagfile = os.path.join(self.module_dir, tagfile)
1221 for line in open(tagfile):
1223 name, url = line.split(':=')
1224 name, git_or_svn_path = name.rsplit('-', 1)
1225 name = svn_to_git_name(name.strip())
1226 modules[name] = (git_or_svn_path.strip(), url.strip())
1231 def get_modules(self, tagfile):
1232 modules = self.__get_modules(tagfile)
1233 for module in modules:
1234 module_type = tag_or_branch = ""
1236 path_type, url = modules[module]
1237 if path_type == "GITPATH":
1238 module_spec = os.path.split(url)[-1].replace(".git","")
1239 name, tag_or_branch, module_type = self.parse_module_spec(module_spec)
1241 tag_or_branch = os.path.split(url)[-1].strip()
1242 if url.find('/tags/') >= 0:
1244 elif url.find('/branches/') >= 0:
1245 module_type = "branch"
1247 modules[module] = {"module_type" : module_type,
1248 "path_type": path_type,
1249 "tag_or_branch": tag_or_branch,
1255 def modules_diff(first, second):
1258 for module in first:
1259 if module not in second:
1260 print "=== module %s missing in right-hand side ==="%module
1262 if first[module]['tag_or_branch'] != second[module]['tag_or_branch']:
1263 diff[module] = (first[module]['tag_or_branch'], second[module]['tag_or_branch'])
1265 first_set = set(first.keys())
1266 second_set = set(second.keys())
1268 new_modules = list(second_set - first_set)
1269 removed_modules = list(first_set - second_set)
1271 return diff, new_modules, removed_modules
1273 def release_changelog(options, buildtag_old, buildtag_new):
1275 tagfile = options.distrotags[0]
1277 print "ERROR: provide a tagfile name (eg. onelab, onelab-k27, planetlab)"
1279 tagfile = "%s-tags.mk" % tagfile
1284 print '= build tag %s to %s =' % (buildtag_old, buildtag_new)
1285 print '== distro %s (%s to %s) ==' % (tagfile, buildtag_old, buildtag_new)
1287 build = Build("build@%s" % buildtag_old, options)
1288 build.init_module_dir()
1289 first = build.get_modules(tagfile)
1291 print ' * from', buildtag_old, build.repository.gitweb()
1293 build = Build("build@%s" % buildtag_new, options)
1294 build.init_module_dir()
1295 second = build.get_modules(tagfile)
1297 print ' * to', buildtag_new, build.repository.gitweb()
1299 diff, new_modules, removed_modules = modules_diff(first, second)
1302 def get_module(name, tag):
1303 if not tag or tag == "trunk":
1304 return Module("%s" % (module), options)
1306 return Module("%s@%s" % (module, tag), options)
1310 print '=== %s - %s to %s : package %s ===' % (tagfile, buildtag_old, buildtag_new, module)
1312 first, second = diff[module]
1313 m = get_module(module, first)
1314 os.system('rm -rf %s' % m.module_dir) # cleanup module dir
1317 if m.repository.type == "svn":
1318 print ' * from', first, m.repository.url()
1320 print ' * from', first, m.repository.gitweb()
1322 specfile = m.main_specname()
1323 (tmpfd, tmpfile) = tempfile.mkstemp()
1324 os.system("cp -f /%s %s" % (specfile, tmpfile))
1326 m = get_module(module, second)
1328 specfile = m.main_specname()
1330 if m.repository.type == "svn":
1331 print ' * to', second, m.repository.url()
1333 print ' * to', second, m.repository.gitweb()
1336 os.system("diff -u %s %s" % (tmpfile, specfile))
1341 for module in new_modules:
1342 print '=== %s : new package in build %s ===' % (tagfile, module)
1344 for module in removed_modules:
1345 print '=== %s : removed package from build %s ===' % (tagfile, module)
1348 def adopt_master (options, args):
1350 for module in options.modules:
1351 modules += module.split()
1352 for module in modules:
1353 modobj=Module(module,options)
1354 for tags_file in args:
1356 print 'adopting master for',module,'in',tags_file
1357 modobj.patch_tags_file(tags_file,'_unused_','master',fine_grain=False)
1359 Command("git diff %s"%" ".join(args),options).run()
1361 ##############################
1364 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1366 module-tools : a set of tools to manage subversion tags and specfile
1367 requires the specfile to either
1368 * define *version* and *taglevel*
1370 * define redirection variables module_version_varname / module_taglevel_varname
1372 by default, the trunk of modules is taken into account
1373 in this case, just mention the module name as <module_desc>
1375 if you wish to work on a branch rather than on the trunk,
1376 you can use something like e.g. Mom:2.1 as <module_desc>
1378 release_usage="""Usage: %prog [options] tag1 .. tagn
1379 Extract release notes from the changes in specfiles between several build tags, latest first
1381 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1382 You can refer to a (build) branch by prepending a colon, like in
1383 release-changelog :4.2 4.2-rc25
1384 You can refer to the build trunk by just mentioning 'trunk', e.g.
1385 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1387 master_usage="""Usage: %prog [options] tag-file[s]
1388 With this command you can adopt one or several masters in your tag files
1389 This should be run in your daily build workdir; no call of git nor svn is done
1391 module-master -m "plewww plcapi" -m Monitor onelab*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 'master' : """locally adopt master or trunk for some modules""",
1412 silent_modes = ['list']
1413 # 'changelog' is for release-changelog
1414 # 'master' is for 'adopt-master'
1415 regular_modes = set(modes.keys()).difference(set(['changelog','master']))
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 for function in Main.modes.keys():
1428 if sys.argv[0].find(function) >= 0:
1432 print "Unsupported command",sys.argv[0]
1433 print "Supported commands:" + " ".join(Main.modes.keys())
1436 usage='undefined usage, mode=%s'%mode
1437 if mode in Main.regular_modes:
1438 usage = Main.module_usage
1439 usage += Main.common_usage
1440 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1441 elif mode=='changelog':
1442 usage = Main.release_usage
1443 usage += Main.common_usage
1444 elif mode=='master':
1445 usage = Main.master_usage
1446 usage += Main.common_usage
1448 parser=OptionParser(usage=usage)
1450 # the 'master' mode is really special and doesn't share any option
1452 parser.add_option("-m","--module",action="append",dest="modules",default=[],
1453 help="modules, can be used several times or with quotes")
1454 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1455 help="run in verbose mode")
1456 (options, args) = parser.parse_args()
1457 options.workdir='unused'
1458 options.dry_run=False
1459 options.mode='master'
1460 if len(args)==0 or len(options.modules)==0:
1463 adopt_master (options,args)
1466 # the other commands (module-* and release-changelog) share the same skeleton
1467 if mode == "tag" or mode == 'branch':
1468 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1469 help="set new version and reset taglevel to 0")
1471 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1472 help="do not update changelog section in specfile when tagging")
1473 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1474 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1475 if mode == "tag" or mode == "sync" :
1476 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1477 help="specify editor")
1479 if mode in ["diff","version"] :
1480 parser.add_option("-W","--www", action="store", dest="www", default=False,
1481 help="export diff in html format, e.g. -W trunk")
1484 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1485 help="just list modules that exhibit differences")
1487 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1488 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1489 help="run on all modules as found in %s"%default_modules_list)
1490 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1491 help="run on all modules found in specified file")
1492 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1493 help="dry run - shell commands are only displayed")
1494 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1495 default=[], nargs=1,type="string",
1496 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1497 -- can be set multiple times, or use quotes""")
1499 parser.add_option("-w","--workdir", action="store", dest="workdir",
1500 default="%s/%s"%(os.getenv("HOME"),"modules"),
1501 help="""name for dedicated working dir - defaults to ~/modules
1502 ** THIS MUST NOT ** be your usual working directory""")
1503 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1504 help="skip safety checks, such as svn updates -- use with care")
1505 parser.add_option("-B","--build-module",action="store",dest="build_module",default=None,
1506 help="specify a build module to owerride the one in the CONFIG")
1508 # default verbosity depending on function - temp
1509 verbose_modes= ['tag', 'sync', 'branch']
1511 if mode not in verbose_modes:
1512 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1513 help="run in verbose mode")
1515 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1516 help="run in quiet (non-verbose) mode")
1517 (options, args) = parser.parse_args()
1519 if not hasattr(options,'dry_run'):
1520 options.dry_run=False
1521 if not hasattr(options,'www'):
1529 if options.all_modules:
1530 options.modules_list=default_modules_list
1531 if options.modules_list:
1532 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1536 Module.init_homedir(options)
1539 if mode in Main.regular_modes:
1540 modules=[ Module(modname,options) for modname in args ]
1541 # hack: create a dummy Module to store errors/warnings
1542 error_module = Module('__errors__',options)
1544 for module in modules:
1545 if len(args)>1 and mode not in Main.silent_modes:
1547 print '========================================',module.friendly_name()
1548 # call the method called do_<mode>
1549 method=Module.__dict__["do_%s"%mode]
1554 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1555 (module.friendly_name(), str(e))
1556 error_module.html_store_title(title)
1559 traceback.print_exc()
1560 print 'Skipping module %s: '%modname,e
1564 modetitle="Changes to tag in %s"%options.www
1565 elif mode == "version":
1566 modetitle="Latest tags in %s"%options.www
1567 modules.append(error_module)
1568 error_module.html_dump_header(modetitle)
1569 for module in modules:
1570 module.html_dump_toc()
1571 Module.html_dump_middle()
1572 for module in modules:
1573 module.html_dump_body()
1574 Module.html_dump_footer()
1576 release_changelog(options, *args)
1579 ####################
1580 if __name__ == "__main__" :
1583 except KeyboardInterrupt: