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 out = Command("svn info %s" % self.path, self.options).output_of()
168 for line in out.split('\n'):
169 if line.startswith("URL:"):
170 return line.split()[1].strip()
173 out = Command("svn info %s" % self.path, self.options).output_of()
174 for line in out.split('\n'):
175 if line.startswith("Repository Root:"):
176 root = line.split()[2].strip()
177 return "%s/%s" % (root, self.pathname())
180 def checkout(cls, remote, local, options, recursive=False):
182 svncommand = "svn co %s %s" % (remote, local)
184 svncommand = "svn co -N %s %s" % (remote, local)
185 Command("rm -rf %s" % local, options).run_silent()
186 Command(svncommand, options).run_fatal()
188 return SvnRepository(local, options)
191 def remote_exists(cls, remote):
192 return os.system("svn list %s &> /dev/null" % remote) == 0
194 def tag_exists(self, tagname):
195 url = "%s/tags/%s" % (self.repo_root(), tagname)
196 return SvnRepository.remote_exists(url)
198 def update(self, subdir="", recursive=True, branch=None):
199 path = os.path.join(self.path, subdir)
201 svncommand = "svn up %s" % path
203 svncommand = "svn up -N %s" % path
204 Command(svncommand, self.options).run_fatal()
206 def commit(self, logfile):
207 # add all new files to the repository
208 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
209 self.path, self.options).output_of()
210 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
212 def to_branch(self, branch):
213 remote = "%s/branches/%s" % (self.repo_root(), branch)
214 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
216 def to_tag(self, tag):
217 remote = "%s/tags/%s" % (self.repo_root(), branch)
218 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
220 def tag(self, tagname, logfile):
221 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
222 self_url = self.url()
223 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
225 def diff(self, f=""):
227 f = os.path.join(self.path, f)
230 return Command("svn diff %s" % f, self.options).output_of(True)
232 def diff_with_tag(self, tagname):
233 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
234 return Command("svn diff %s %s" % (tag_url, self.url()),
235 self.options).output_of(True)
237 def revert(self, f=""):
239 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
242 Command("svn revert %s -R" % self.path, self.options).run_fatal()
243 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
244 self.path, self.options).run_silent()
247 command="svn status %s" % self.path
248 return len(Command(command,self.options).output_of(True)) == 0
251 return os.path.exists(os.path.join(self.path, ".svn"))
257 def __init__(self, path, options):
259 self.options = options
262 return os.path.basename(self.path)
265 return self.repo_root()
268 c = Command("git show | grep commit | awk '{print $2;}'", self.options)
269 out = self.__run_in_repo(c.output_of).strip()
270 return "http://git.onelab.eu/?p=%s.git;a=commit;h=%s" % (self.pathname(), out)
273 c = Command("git remote show origin", self.options)
274 out = self.__run_in_repo(c.output_of)
275 for line in out.split('\n'):
276 if line.strip().startswith("Fetch URL:"):
277 return line.split()[2]
280 def checkout(cls, remote, local, options, depth=0):
281 Command("rm -rf %s" % local, options).run_silent()
282 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
283 return GitRepository(local, options)
286 def remote_exists(cls, remote):
287 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
289 def tag_exists(self, tagname):
290 command = 'git tag -l | grep "^%s$"' % tagname
291 c = Command(command, self.options)
292 out = self.__run_in_repo(c.output_of, with_stderr=True)
295 def __run_in_repo(self, fun, *args, **kwargs):
298 ret = fun(*args, **kwargs)
302 def __run_command_in_repo(self, command, ignore_errors=False):
303 c = Command(command, self.options)
305 return self.__run_in_repo(c.output_of)
307 return self.__run_in_repo(c.run_fatal)
309 def __is_commit_id(self, id):
310 c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
311 ret = self.__run_in_repo(c.output_of, with_stderr=False)
312 if ret.strip() == id:
316 def update(self, subdir=None, recursive=None, branch="master"):
317 if branch == "master":
318 self.__run_command_in_repo("git checkout %s" % branch)
320 self.to_branch(branch, remote=True)
321 self.__run_command_in_repo("git fetch origin --tags")
322 self.__run_command_in_repo("git fetch origin")
323 if not self.__is_commit_id(branch):
324 # we don't need to merge anythign for commit ids.
325 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
327 def to_branch(self, branch, remote=True):
330 command = "git branch --track %s origin/%s" % (branch, branch)
331 c = Command(command, self.options)
332 self.__run_in_repo(c.output_of, with_stderr=True)
333 return self.__run_command_in_repo("git checkout %s" % branch)
335 def to_tag(self, tag):
337 return self.__run_command_in_repo("git checkout %s" % tag)
339 def tag(self, tagname, logfile):
340 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
343 def diff(self, f=""):
344 c = Command("git diff %s" % f, self.options)
345 return self.__run_in_repo(c.output_of, with_stderr=True)
347 def diff_with_tag(self, tagname):
348 c = Command("git diff %s" % tagname, self.options)
349 return self.__run_in_repo(c.output_of, with_stderr=True)
351 def commit(self, logfile, branch="master"):
352 self.__run_command_in_repo("git add .", ignore_errors=True)
353 self.__run_command_in_repo("git add -u", ignore_errors=True)
354 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
355 if branch == "master" or self.__is_commit_id(branch):
356 self.__run_command_in_repo("git push")
358 self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
359 self.__run_command_in_repo("git push --tags")
361 def revert(self, f=""):
363 self.__run_command_in_repo("git checkout %s" % f)
366 self.__run_command_in_repo("git --no-pager reset --hard")
367 self.__run_command_in_repo("git --no-pager clean -f")
372 s="nothing to commit (working directory clean)"
373 return Command(command, self.options).output_of(True).find(s) >= 0
374 return self.__run_in_repo(check_commit)
377 return os.path.exists(os.path.join(self.path, ".git"))
381 """ Generic repository """
382 supported_repo_types = [SvnRepository, GitRepository]
384 def __init__(self, path, options):
386 self.options = options
387 for repo in self.supported_repo_types:
388 self.repo = repo(self.path, self.options)
389 if self.repo.is_valid():
393 def has_moved_to_git(cls, module, config):
394 module = svn_to_git_name(module)
395 # check if the module is already in Git
396 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
397 return GitRepository.remote_exists(Module.git_remote_dir(module))
401 def remote_exists(cls, remote):
402 for repo in Repository.supported_repo_types:
403 if repo.remote_exists(remote):
407 def __getattr__(self, attr):
408 return getattr(self.repo, attr)
412 # support for tagged module is minimal, and is for the Build class only
415 svn_magic_line="--This line, and those below, will be ignored--"
416 setting_tag_format = "Setting tag %s"
418 redirectors=[ # ('module_name_varname','name'),
419 ('module_version_varname','version'),
420 ('module_taglevel_varname','taglevel'), ]
422 # where to store user's config
423 config_storage="CONFIG"
428 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
429 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
430 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
431 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
432 ("build", "Enter the name of your build module","build"),
433 ('username',"Enter your firstname and lastname for changelogs",""),
434 ("email","Enter your email address for changelogs",""),
438 def prompt_config_option(cls, key, message, default):
439 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
442 def prompt_config (cls):
443 for (key,message,default) in cls.configKeys:
445 while not cls.config[key]:
446 cls.prompt_config_option(key, message, default)
448 # for parsing module spec name:branch
449 matcher_branch_spec=re.compile("\A(?P<name>[\w\.\-\/]+):(?P<branch>[\w\.\-]+)\Z")
450 # special form for tagged module - for Build
451 matcher_tag_spec=re.compile("\A(?P<name>[\w\.\-\/]+)@(?P<tagname>[\w\.\-]+)\Z")
453 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
456 def parse_module_spec(cls, module_spec):
457 name = branch_or_tagname = module_type = ""
459 attempt=Module.matcher_branch_spec.match(module_spec)
461 module_type = "branch"
462 name=attempt.group('name')
463 branch_or_tagname=attempt.group('branch')
465 attempt=Module.matcher_tag_spec.match(module_spec)
468 name=attempt.group('name')
469 branch_or_tagname=attempt.group('tagname')
472 return name, branch_or_tagname, module_type
475 def __init__ (self,module_spec,options):
477 self.pathname, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
478 self.name = os.path.basename(self.pathname)
480 if module_type == "branch":
481 self.branch=branch_or_tagname
482 elif module_type == "tag":
483 self.tagname=branch_or_tagname
485 # when available prefer to use git module name internally
486 self.name = svn_to_git_name(self.name)
489 self.module_dir="%s/%s"%(options.workdir,self.pathname)
490 self.repository = None
493 def run (self,command):
494 return Command(command,self.options).run()
495 def run_fatal (self,command):
496 return Command(command,self.options).run_fatal()
497 def run_prompt (self,message,fun, *args):
498 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
499 if not self.options.verbose:
501 choice=prompt(message,True,('s','how'))
505 elif choice is False:
506 print 'About to run function:', fun_msg
508 question=message+" - want to run function: " + fun_msg
509 if prompt(question,True):
512 def friendly_name (self):
513 if hasattr(self,'branch'):
514 return "%s:%s"%(self.pathname,self.branch)
515 elif hasattr(self,'tagname'):
516 return "%s@%s"%(self.pathname,self.tagname)
521 def git_remote_dir (cls, name):
522 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
525 def svn_remote_dir (cls, name):
526 name = git_to_svn_name(name)
527 svn = cls.config['svnpath']
528 if svn.endswith('/'):
529 return "%s%s" % (svn, name)
530 return "%s/%s" % (svn, name)
532 def svn_selected_remote(self):
533 svn_name = git_to_svn_name(self.name)
534 remote = self.svn_remote_dir(svn_name)
535 if hasattr(self,'branch'):
536 remote = "%s/branches/%s" % (remote, self.branch)
537 elif hasattr(self,'tagname'):
538 remote = "%s/tags/%s" % (remote, self.tagname)
540 remote = "%s/trunk" % remote
545 def init_homedir (cls, options):
546 if options.verbose and options.mode not in Main.silent_modes:
547 print 'Checking for', options.workdir
548 storage="%s/%s"%(options.workdir, cls.config_storage)
549 # sanity check. Either the topdir exists AND we have a config/storage
550 # or topdir does not exist and we create it
551 # to avoid people use their own daily svn repo
552 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
553 print """The directory %s exists and has no CONFIG file
554 If this is your regular working directory, please provide another one as the
555 module-* commands need a fresh working dir. Make sure that you do not use
556 that for other purposes than tagging""" % options.workdir
559 def checkout_build():
560 print "Checking out build module..."
561 remote = cls.git_remote_dir(cls.config['build'])
562 local = os.path.join(options.workdir, cls.config['build'])
563 GitRepository.checkout(remote, local, options, depth=1)
568 for (key,message,default) in Module.configKeys:
569 f.write("%s=%s\n"%(key,Module.config[key]))
572 print 'Stored',storage
573 Command("cat %s"%storage,options).run()
578 for line in f.readlines():
579 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
580 Module.config[key]=value
583 # owerride config variables using options.
584 if options.build_module:
585 Module.config['build'] = options.build_module
587 if not os.path.isdir (options.workdir):
588 print "Cannot find",options.workdir,"let's create it"
589 Command("mkdir -p %s" % options.workdir, options).run_silent()
595 # check missing config options
597 for (key,message,default) in cls.configKeys:
598 if not Module.config.has_key(key):
599 print "Configuration changed for module-tools"
600 cls.prompt_config_option(key, message, default)
604 Command("rm -rf %s" % options.workdir, options).run_silent()
605 Command("mkdir -p %s" % options.workdir, options).run_silent()
609 build_dir = os.path.join(options.workdir, cls.config['build'])
610 if not os.path.isdir(build_dir):
613 build = Repository(build_dir, options)
614 if not build.is_clean():
615 print "build module needs a revert"
620 if options.verbose and options.mode not in Main.silent_modes:
621 print '******** Using config'
622 for (key,message,default) in Module.configKeys:
623 print '\t',key,'=',Module.config[key]
625 def init_module_dir (self):
626 if self.options.verbose:
627 print 'Checking for',self.module_dir
629 if not os.path.isdir (self.module_dir):
630 if Repository.has_moved_to_git(self.pathname, Module.config):
631 self.repository = GitRepository.checkout(self.git_remote_dir(self.pathname),
635 remote = self.svn_selected_remote()
636 self.repository = SvnRepository.checkout(remote,
638 self.options, recursive=False)
640 self.repository = Repository(self.module_dir, self.options)
641 if self.repository.type == "svn":
642 # check if module has moved to git
643 if Repository.has_moved_to_git(self.pathname, Module.config):
644 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
645 self.init_module_dir()
646 # check if we have the required branch/tag
647 if self.repository.url() != self.svn_selected_remote():
648 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
649 self.init_module_dir()
651 elif self.repository.type == "git":
652 if hasattr(self,'branch'):
653 self.repository.to_branch(self.branch)
654 elif hasattr(self,'tagname'):
655 self.repository.to_tag(self.tagname)
658 raise Exception, 'Cannot find %s - check module name'%self.module_dir
661 def revert_module_dir (self):
662 if self.options.fast_checks:
663 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
665 if self.options.verbose:
666 print 'Checking whether', self.module_dir, 'needs being reverted'
668 if not self.repository.is_clean():
669 self.repository.revert()
671 def update_module_dir (self):
672 if self.options.fast_checks:
673 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
675 if self.options.verbose:
676 print 'Updating', self.module_dir
678 if hasattr(self,'branch'):
679 self.repository.update(branch=self.branch)
680 elif hasattr(self,'tagname'):
681 self.repository.update(branch=self.tagname)
683 self.repository.update()
685 def main_specname (self):
686 attempt="%s/%s.spec"%(self.module_dir,self.name)
687 if os.path.isfile (attempt):
689 pattern1="%s/*.spec"%self.module_dir
690 level1=glob(pattern1)
693 pattern2="%s/*/*.spec"%self.module_dir
694 level2=glob(pattern2)
698 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.pathname,pattern1,pattern2)
700 def all_specnames (self):
701 level1=glob("%s/*.spec" % self.module_dir)
702 if level1: return level1
703 level2=glob("%s/*/*.spec" % self.module_dir)
706 def parse_spec (self, specfile, varnames):
707 if self.options.verbose:
708 print 'Parsing',specfile,
714 for line in f.readlines():
715 attempt=Module.matcher_rpm_define.match(line)
717 (define,var,value)=attempt.groups()
721 if self.options.debug:
722 print 'found',len(result),'keys'
723 for (k,v) in result.iteritems():
727 # stores in self.module_name_varname the rpm variable to be used for the module's name
728 # and the list of these names in self.varnames
729 def spec_dict (self):
730 specfile=self.main_specname()
731 redirector_keys = [ varname for (varname,default) in Module.redirectors]
732 redirect_dict = self.parse_spec(specfile,redirector_keys)
733 if self.options.debug:
734 print '1st pass parsing done, redirect_dict=',redirect_dict
736 for (varname,default) in Module.redirectors:
737 if redirect_dict.has_key(varname):
738 setattr(self,varname,redirect_dict[varname])
739 varnames += [redirect_dict[varname]]
741 setattr(self,varname,default)
742 varnames += [ default ]
743 self.varnames = varnames
744 result = self.parse_spec (specfile,self.varnames)
745 if self.options.debug:
746 print '2st pass parsing done, varnames=',varnames,'result=',result
749 def patch_spec_var (self, patch_dict,define_missing=False):
750 for specfile in self.all_specnames():
751 # record the keys that were changed
752 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
753 newspecfile=specfile+".new"
754 if self.options.verbose:
755 print 'Patching',specfile,'for',patch_dict.keys()
757 new=open(newspecfile,"w")
759 for line in spec.readlines():
760 attempt=Module.matcher_rpm_define.match(line)
762 (define,var,value)=attempt.groups()
763 if var in patch_dict.keys():
764 if self.options.debug:
765 print 'rewriting %s as %s'%(var,patch_dict[var])
766 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
771 for (key,was_changed) in changed.iteritems():
773 if self.options.debug:
774 print 'rewriting missing %s as %s'%(key,patch_dict[key])
775 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
778 os.rename(newspecfile,specfile)
780 # returns all lines until the magic line
781 def unignored_lines (self, logfile):
783 white_line_matcher = re.compile("\A\s*\Z")
784 for logline in file(logfile).readlines():
785 if logline.strip() == Module.svn_magic_line:
787 elif white_line_matcher.match(logline):
790 result.append(logline.strip()+'\n')
793 # creates a copy of the input with only the unignored lines
794 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
796 f.write(self.setting_tag_format%new_tag_name + '\n')
797 for line in self.unignored_lines(filein):
801 def insert_changelog (self, logfile, oldtag, newtag):
802 for specfile in self.all_specnames():
803 newspecfile=specfile+".new"
804 if self.options.verbose:
805 print 'Inserting changelog from %s into %s'%(logfile,specfile)
807 new=open(newspecfile,"w")
808 for line in spec.readlines():
810 if re.compile('%changelog').match(line):
811 dateformat="* %a %b %d %Y"
812 datepart=time.strftime(dateformat)
813 logpart="%s <%s> - %s"%(Module.config['username'],
814 Module.config['email'],
816 new.write(datepart+" "+logpart+"\n")
817 for logline in self.unignored_lines(logfile):
818 new.write("- " + logline)
822 os.rename(newspecfile,specfile)
824 def show_dict (self, spec_dict):
825 if self.options.verbose:
826 for (k,v) in spec_dict.iteritems():
829 def last_tag (self, spec_dict):
831 return "%s-%s" % (spec_dict[self.module_version_varname],
832 spec_dict[self.module_taglevel_varname])
834 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
836 def tag_name (self, spec_dict, old_svn_name=False):
837 base_tag_name = self.name
839 base_tag_name = git_to_svn_name(self.name)
840 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
843 ##############################
844 # using fine_grain means replacing only those instances that currently refer to this tag
845 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
846 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
847 newtagsfile=tagsfile+".new"
849 new=open(newtagsfile,"w")
852 # fine-grain : replace those lines that refer to oldname
854 if self.options.verbose:
855 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
856 matcher=re.compile("^(.*)%s(.*)"%oldname)
857 for line in tags.readlines():
858 if not matcher.match(line):
861 (begin,end)=matcher.match(line).groups()
862 new.write(begin+newname+end+"\n")
864 # brute-force : change uncommented lines that define <module>-SVNPATH
866 if self.options.verbose:
867 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.pathname,tagsfile),
868 pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
869 %(self.name,self.name)
870 matcher_module=re.compile(pattern)
871 for line in tags.readlines():
872 attempt=matcher_module.match(line)
874 if line.find("-GITPATH") >= 0:
875 modulepath = "%s-GITPATH"%self.name
876 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.pathname,newname)
878 modulepath = "%s-SVNPATH"%self.name
879 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
880 if self.options.verbose:
881 print ' ' + modulepath,
882 new.write(replacement)
888 os.rename(newtagsfile,tagsfile)
889 if self.options.verbose: print "%d changes"%matches
892 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
893 if self.options.verbose:
894 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
896 found_tagname = tagname
897 found = self.repository.tag_exists(tagname)
898 if not found and old_svn_tag_name:
899 if self.options.verbose:
901 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
902 found = self.repository.tag_exists(old_svn_tag_name)
904 found_tagname = old_svn_tag_name
906 if (found and need_it) or (not found and not need_it):
907 if self.options.verbose:
909 if found: print "- found"
910 else: print "- not found"
912 if self.options.verbose:
915 raise Exception, "tag (%s) is already there" % tagname
917 raise Exception, "can not find required tag (%s)" % tagname
922 ##############################
924 self.init_module_dir()
925 self.revert_module_dir()
926 self.update_module_dir()
928 spec_dict = self.spec_dict()
929 self.show_dict(spec_dict)
932 old_tag_name = self.tag_name(spec_dict)
933 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
935 if (self.options.new_version):
936 # new version set on command line
937 spec_dict[self.module_version_varname] = self.options.new_version
938 spec_dict[self.module_taglevel_varname] = 0
941 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
942 spec_dict[self.module_taglevel_varname] = new_taglevel
944 new_tag_name = self.tag_name(spec_dict)
947 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
948 new_tag_name = self.check_tag(new_tag_name, need_it=False)
951 diff_output = self.repository.diff_with_tag(old_tag_name)
952 if len(diff_output) == 0:
953 if not prompt ("No pending difference in module %s, want to tag anyway"%self.pathname,False):
956 # side effect in trunk's specfile
957 self.patch_spec_var(spec_dict)
959 # prepare changelog file
960 # we use the standard subversion magic string (see svn_magic_line)
961 # so we can provide useful information, such as version numbers and diff
963 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
964 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
965 setting_tag_line=Module.setting_tag_format%new_tag_name
966 file(changelog,"w").write("""
969 Please write a changelog for this new tag in the section above
970 """%(Module.svn_magic_line,setting_tag_line))
972 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
973 file(changelog,"a").write('DIFF=========\n' + diff_output)
975 if self.options.debug:
979 self.run("%s %s"%(self.options.editor,changelog))
980 # strip magic line in second file - looks like svn has changed its magic line with 1.6
981 # so we do the job ourselves
982 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
983 # insert changelog in spec
984 if self.options.changelog:
985 self.insert_changelog (changelog,old_tag_name,new_tag_name)
988 build_path = os.path.join(self.options.workdir,
989 Module.config['build'])
990 build = Repository(build_path, self.options)
991 if self.options.build_branch:
992 build.to_branch(self.options.build_branch)
993 if not build.is_clean():
996 tagsfiles=glob(build.path+"/*-tags.mk")
997 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
1001 for tagsfile in tagsfiles:
1002 status=tagsdict[tagsfile]
1003 basename=os.path.basename(tagsfile)
1004 print ".................... Dealing with %s"%basename
1005 while tagsdict[tagsfile] == 'todo' :
1006 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
1007 [ ('y','es'), ('n', 'ext'), ('f','orce'),
1008 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
1011 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1013 print 'Done with %s'%os.path.basename(tagsfile)
1014 tagsdict[tagsfile]='done'
1016 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1018 print build.diff(f=os.path.basename(tagsfile))
1020 build.revert(f=tagsfile)
1022 self.run("cat %s"%tagsfile)
1025 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1026 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1027 d: show current diff for this tag file
1028 r: revert that tag file
1029 c: cat the current tag file
1030 n: move to next file"""%locals()
1032 if prompt("Want to review changes on tags files",False):
1033 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1038 def diff_all_changes():
1040 print self.repository.diff()
1042 def commit_all_changes(log):
1043 if hasattr(self,'branch'):
1044 self.repository.commit(log, branch=self.branch)
1046 self.repository.commit(log)
1049 self.run_prompt("Review module and build", diff_all_changes)
1050 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1051 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1053 if self.options.debug:
1054 print 'Preserving',changelog,'and stripped',changelog_svn
1056 os.unlink(changelog)
1057 os.unlink(changelog_svn)
1060 ##############################
1061 def do_version (self):
1062 self.init_module_dir()
1063 self.revert_module_dir()
1064 self.update_module_dir()
1065 spec_dict = self.spec_dict()
1066 if self.options.www:
1067 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1068 self.last_tag(spec_dict)))
1069 for varname in self.varnames:
1070 if not spec_dict.has_key(varname):
1071 self.html_print ('Could not find %%define for %s'%varname)
1074 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1075 self.html_print ("%-16s %s"%('url',self.repository.url()))
1076 if self.options.verbose:
1077 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1078 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1079 self.html_print_end()
1082 ##############################
1084 self.init_module_dir()
1085 self.revert_module_dir()
1086 self.update_module_dir()
1087 spec_dict = self.spec_dict()
1088 self.show_dict(spec_dict)
1091 tag_name = self.tag_name(spec_dict)
1092 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1095 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1097 if self.options.verbose:
1098 print 'Getting diff'
1099 diff_output = self.repository.diff_with_tag(tag_name)
1101 if self.options.list:
1105 thename=self.friendly_name()
1107 if self.options.www and diff_output:
1108 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1109 thename,self.last_tag(spec_dict),len(diff_output)))
1111 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1112 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1113 self.html_store_pre (diff_output)
1114 elif not self.options.www:
1115 print 'x'*30,'module',thename
1116 print 'x'*20,'<',tag_name
1117 print 'x'*20,'>',thename
1120 ##############################
1121 # store and restitute html fragments
1123 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1126 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1129 def html_quote (text):
1130 return text.replace('&','&').replace('<','<').replace('>','>')
1132 # only the fake error module has multiple titles
1133 def html_store_title (self, title):
1134 if not hasattr(self,'titles'): self.titles=[]
1135 self.titles.append(title)
1137 def html_store_raw (self, html):
1138 if not hasattr(self,'body'): self.body=''
1141 def html_store_pre (self, text):
1142 if not hasattr(self,'body'): self.body=''
1143 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1145 def html_print (self, txt):
1146 if not self.options.www:
1149 if not hasattr(self,'in_list') or not self.in_list:
1150 self.html_store_raw('<ul>')
1152 self.html_store_raw('<li>'+txt+'</li>')
1154 def html_print_end (self):
1155 if self.options.www:
1156 self.html_store_raw ('</ul>')
1159 def html_dump_header(title):
1160 nowdate=time.strftime("%Y-%m-%d")
1161 nowtime=time.strftime("%H:%M (%Z)")
1162 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1163 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1166 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1167 <style type="text/css">
1168 body { font-family:georgia, serif; }
1169 h1 {font-size: large; }
1170 p.title {font-size: x-large; }
1171 span.error {text-weight:bold; color: red; }
1175 <p class='title'> %s - status on %s at %s</p>
1177 """%(title,title,nowdate,nowtime)
1180 def html_dump_middle():
1184 def html_dump_footer():
1185 print "</body></html"
1187 def html_dump_toc(self):
1188 if hasattr(self,'titles'):
1189 for title in self.titles:
1190 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1192 def html_dump_body(self):
1193 if hasattr(self,'titles'):
1194 for title in self.titles:
1195 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1196 if hasattr(self,'body'):
1198 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1202 class Build(Module):
1204 def __get_modules(self, tagfile):
1205 self.init_module_dir()
1208 tagfile = os.path.join(self.module_dir, tagfile)
1209 for line in open(tagfile):
1211 name, url = line.split(':=')
1212 name, git_or_svn_path = name.rsplit('-', 1)
1213 name = svn_to_git_name(name.strip())
1214 modules[name] = (git_or_svn_path.strip(), url.strip())
1219 def get_modules(self, tagfile):
1220 modules = self.__get_modules(tagfile)
1221 for module in modules:
1222 module_type = tag_or_branch = ""
1224 path_type, url = modules[module]
1225 if path_type == "GITPATH":
1226 module_spec = os.path.split(url)[-1].replace(".git","")
1227 name, tag_or_branch, module_type = self.parse_module_spec(module_spec)
1229 tag_or_branch = os.path.split(url)[-1].strip()
1230 if url.find('/tags/') >= 0:
1232 elif url.find('/branches/') >= 0:
1233 module_type = "branch"
1235 modules[module] = {"module_type" : module_type,
1236 "path_type": path_type,
1237 "tag_or_branch": tag_or_branch,
1243 def modules_diff(first, second):
1246 for module in first:
1247 if module not in second:
1248 print "=== module %s missing in right-hand side ==="%module
1250 if first[module]['tag_or_branch'] != second[module]['tag_or_branch']:
1251 diff[module] = (first[module]['tag_or_branch'], second[module]['tag_or_branch'])
1253 first_set = set(first.keys())
1254 second_set = set(second.keys())
1256 new_modules = list(second_set - first_set)
1257 removed_modules = list(first_set - second_set)
1259 return diff, new_modules, removed_modules
1261 def release_changelog(options, buildtag_old, buildtag_new):
1263 tagfile = options.distrotags[0]
1265 print "ERROR: provide a tagfile name (eg. onelab, onelab-k27, planetlab)"
1267 tagfile = "%s-tags.mk" % tagfile
1272 print '= build tag %s to %s =' % (buildtag_old, buildtag_new)
1273 print '== distro %s (%s to %s) ==' % (tagfile, buildtag_old, buildtag_new)
1275 build = Build("build@%s" % buildtag_old, options)
1276 build.init_module_dir()
1277 first = build.get_modules(tagfile)
1279 print ' * from', buildtag_old, build.repository.gitweb()
1281 build = Build("build@%s" % buildtag_new, options)
1282 build.init_module_dir()
1283 second = build.get_modules(tagfile)
1285 print ' * to', buildtag_new, build.repository.gitweb()
1287 diff, new_modules, removed_modules = modules_diff(first, second)
1290 def get_module(name, tag):
1291 if not tag or tag == "trunk":
1292 return Module("%s" % (module), options)
1294 return Module("%s@%s" % (module, tag), options)
1298 print '=== %s - %s to %s : package %s ===' % (tagfile, buildtag_old, buildtag_new, module)
1300 first, second = diff[module]
1301 m = get_module(module, first)
1302 os.system('rm -rf %s' % m.module_dir) # cleanup module dir
1305 if m.repository.type == "svn":
1306 print ' * from', first, m.repository.url()
1308 print ' * from', first, m.repository.gitweb()
1310 specfile = m.main_specname()
1311 (tmpfd, tmpfile) = tempfile.mkstemp()
1312 os.system("cp -f /%s %s" % (specfile, tmpfile))
1314 m = get_module(module, second)
1316 specfile = m.main_specname()
1318 if m.repository.type == "svn":
1319 print ' * to', second, m.repository.url()
1321 print ' * to', second, m.repository.gitweb()
1324 os.system("diff -u %s %s" % (tmpfile, specfile))
1329 for module in new_modules:
1330 print '=== %s : new package in build %s ===' % (tagfile, module)
1332 for module in removed_modules:
1333 print '=== %s : removed package from build %s ===' % (tagfile, module)
1336 def adopt_master (options, args):
1338 for module in options.modules:
1339 modules += module.split()
1340 for module in modules:
1341 modobj=Module(module,options)
1342 for tags_file in args:
1344 print 'adopting master for',module,'in',tags_file
1345 modobj.patch_tags_file(tags_file,'_unused_','master',fine_grain=False)
1347 Command("git diff %s"%" ".join(args),options).run()
1349 ##############################
1352 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1354 module-tools : a set of tools to manage subversion tags and specfile
1355 requires the specfile to either
1356 * define *version* and *taglevel*
1358 * define redirection variables module_version_varname / module_taglevel_varname
1360 by default, the trunk of modules is taken into account
1361 in this case, just mention the module name as <module_desc>
1363 if you wish to work on a branch rather than on the trunk,
1364 you can use something like e.g. Mom:2.1 as <module_desc>
1366 release_usage="""Usage: %prog [options] tag1 .. tagn
1367 Extract release notes from the changes in specfiles between several build tags, latest first
1369 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1370 You can refer to a (build) branch by prepending a colon, like in
1371 release-changelog :4.2 4.2-rc25
1372 You can refer to the build trunk by just mentioning 'trunk', e.g.
1373 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1375 master_usage="""Usage: %prog [options] tag-file[s]
1376 With this command you can adopt one or several masters in your tag files
1377 This should be run in your daily build workdir; no call of git nor svn is done
1379 module-master -m "plewww plcapi" -m Monitor onelab*tags.mk
1381 common_usage="""More help:
1382 see http://svn.planet-lab.org/wiki/ModuleTools"""
1385 'list' : "displays a list of available tags or branches",
1386 'version' : "check latest specfile and print out details",
1387 'diff' : "show difference between module (trunk or branch) and latest tag",
1388 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1389 create new tag and and monitor its adoption in build/*-tags.mk""",
1390 'branch' : """create a branch for this module, from the latest tag on the trunk,
1391 and change trunk's version number to reflect the new branch name;
1392 you can specify the new branch name by using module:branch""",
1393 'sync' : """create a tag from the module
1394 this is a last resort option, mostly for repairs""",
1395 'changelog' : """extract changelog between build tags
1396 expected arguments are a list of tags""",
1397 'master' : """locally adopt master or trunk for some modules""",
1400 silent_modes = ['list']
1401 # 'changelog' is for release-changelog
1402 # 'master' is for 'adopt-master'
1403 regular_modes = set(modes.keys()).difference(set(['changelog','master']))
1406 def optparse_list (option, opt, value, parser):
1408 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1410 setattr(parser.values,option.dest,value.split())
1415 for function in Main.modes.keys():
1416 if sys.argv[0].find(function) >= 0:
1420 print "Unsupported command",sys.argv[0]
1421 print "Supported commands:" + " ".join(Main.modes.keys())
1424 usage='undefined usage, mode=%s'%mode
1425 if mode in Main.regular_modes:
1426 usage = Main.module_usage
1427 usage += Main.common_usage
1428 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1429 elif mode=='changelog':
1430 usage = Main.release_usage
1431 usage += Main.common_usage
1432 elif mode=='master':
1433 usage = Main.master_usage
1434 usage += Main.common_usage
1436 parser=OptionParser(usage=usage)
1438 # the 'master' mode is really special and doesn't share any option
1440 parser.add_option("-m","--module",action="append",dest="modules",default=[],
1441 help="modules, can be used several times or with quotes")
1442 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1443 help="run in verbose mode")
1444 (options, args) = parser.parse_args()
1445 options.workdir='unused'
1446 options.dry_run=False
1447 options.mode='master'
1448 if len(args)==0 or len(options.modules)==0:
1451 adopt_master (options,args)
1454 # the other commands (module-* and release-changelog) share the same skeleton
1455 if mode == "tag" or mode == 'branch':
1456 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1457 help="set new version and reset taglevel to 0")
1459 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1460 help="do not update changelog section in specfile when tagging")
1461 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1462 help="specify a build branch; used for locating the *tags.mk files where adoption is to take place")
1463 if mode == "tag" or mode == "sync" :
1464 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1465 help="specify editor")
1467 if mode in ["diff","version"] :
1468 parser.add_option("-W","--www", action="store", dest="www", default=False,
1469 help="export diff in html format, e.g. -W trunk")
1472 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1473 help="just list modules that exhibit differences")
1475 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1476 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1477 help="run on all modules as found in %s"%default_modules_list)
1478 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1479 help="run on all modules found in specified file")
1480 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1481 help="dry run - shell commands are only displayed")
1482 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1483 default=[], nargs=1,type="string",
1484 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1485 -- can be set multiple times, or use quotes""")
1487 parser.add_option("-w","--workdir", action="store", dest="workdir",
1488 default="%s/%s"%(os.getenv("HOME"),"modules"),
1489 help="""name for dedicated working dir - defaults to ~/modules
1490 ** THIS MUST NOT ** be your usual working directory""")
1491 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1492 help="skip safety checks, such as svn updates -- use with care")
1493 parser.add_option("-B","--build-module",action="store",dest="build_module",default=None,
1494 help="specify a build module to owerride the one in the CONFIG")
1496 # default verbosity depending on function - temp
1497 verbose_modes= ['tag', 'sync', 'branch']
1499 if mode not in verbose_modes:
1500 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1501 help="run in verbose mode")
1503 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1504 help="run in quiet (non-verbose) mode")
1505 (options, args) = parser.parse_args()
1507 if not hasattr(options,'dry_run'):
1508 options.dry_run=False
1509 if not hasattr(options,'www'):
1517 if options.all_modules:
1518 options.modules_list=default_modules_list
1519 if options.modules_list:
1520 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1524 Module.init_homedir(options)
1527 if mode in Main.regular_modes:
1528 modules=[ Module(modname,options) for modname in args ]
1529 # hack: create a dummy Module to store errors/warnings
1530 error_module = Module('__errors__',options)
1532 for module in modules:
1533 if len(args)>1 and mode not in Main.silent_modes:
1535 print '========================================',module.friendly_name()
1536 # call the method called do_<mode>
1537 method=Module.__dict__["do_%s"%mode]
1542 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1543 (module.friendly_name(), str(e))
1544 error_module.html_store_title(title)
1547 traceback.print_exc()
1548 print 'Skipping module %s: '%modname,e
1552 modetitle="Changes to tag in %s"%options.www
1553 elif mode == "version":
1554 modetitle="Latest tags in %s"%options.www
1555 modules.append(error_module)
1556 error_module.html_dump_header(modetitle)
1557 for module in modules:
1558 module.html_dump_toc()
1559 Module.html_dump_middle()
1560 for module in modules:
1561 module.html_dump_body()
1562 Module.html_dump_footer()
1564 release_changelog(options, *args)
1567 ####################
1568 if __name__ == "__main__" :
1571 except KeyboardInterrupt: