7 from optparse import OptionParser
9 # HARDCODED NAME CHANGES
11 # Moving to git we decided to rename some of the repositories. Here is
12 # a map of name changes applied in git repositories.
13 RENAMED_SVN_MODULES = {
18 def svn_to_git_name(module):
19 if RENAMED_SVN_MODULES.has_key(module):
20 return RENAMED_SVN_MODULES[module]
23 def git_to_svn_name(module):
24 for key in RENAMED_SVN_MODULES:
25 if module == RENAMED_SVN_MODULES[key]:
30 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
31 def prompt (question,default=True,other_choices=[],allow_outside=False):
32 if not isinstance (other_choices,list):
33 other_choices = [ other_choices ]
34 chars = [ c for (c,rest) in other_choices ]
38 if default is True: choices.append('[y]')
39 else : choices.append('y')
41 if default is False: choices.append('[n]')
42 else : choices.append('n')
44 for (char,choice) in other_choices:
46 choices.append("["+char+"]"+choice)
48 choices.append("<"+char+">"+choice)
50 answer=raw_input(question + " " + "/".join(choices) + " ? ")
53 answer=answer[0].lower()
55 if 'y' in chars: return 'y'
58 if 'n' in chars: return 'n'
61 for (char,choice) in other_choices:
66 return prompt(question,default,other_choices)
72 editor = os.environ['EDITOR']
80 def print_fold (line):
81 while len(line) >= fold_length:
82 print line[:fold_length],'\\'
83 line=line[fold_length:]
87 def __init__ (self,command,options):
90 self.tmp="/tmp/command-%d"%os.getpid()
93 if self.options.dry_run:
94 print 'dry_run',self.command
96 if self.options.verbose and self.options.mode not in Main.silent_modes:
97 print '+',self.command
99 return os.system(self.command)
101 def run_silent (self):
102 if self.options.dry_run:
103 print 'dry_run',self.command
105 if self.options.verbose:
106 print '+',self.command,' .. ',
108 retcod=os.system(self.command + " &> " + self.tmp)
110 print "FAILED ! -- out+err below (command was %s)"%self.command
111 os.system("cat " + self.tmp)
112 print "FAILED ! -- end of quoted output"
113 elif self.options.verbose:
119 if self.run_silent() !=0:
120 raise Exception,"Command %s failed"%self.command
122 # returns stdout, like bash's $(mycommand)
123 def output_of (self,with_stderr=False):
124 if self.options.dry_run:
125 print 'dry_run',self.command
126 return 'dry_run output'
127 tmp="/tmp/status-%d"%os.getpid()
128 if self.options.debug:
129 print '+',self.command,' .. ',
138 result=file(tmp).read()
140 if self.options.debug:
148 def __init__(self, path, options):
150 self.options = options
153 return os.path.basename(self.path)
156 out = Command("svn info %s" % self.path, self.options).output_of()
157 for line in out.split('\n'):
158 if line.startswith("URL:"):
159 return line.split()[1].strip()
162 out = Command("svn info %s" % self.path, self.options).output_of()
163 for line in out.split('\n'):
164 if line.startswith("Repository Root:"):
165 root = line.split()[2].strip()
166 return "%s/%s" % (root, self.name())
169 def checkout(cls, remote, local, options, recursive=False):
171 svncommand = "svn co %s %s" % (remote, local)
173 svncommand = "svn co -N %s %s" % (remote, local)
174 Command("rm -rf %s" % local, options).run_silent()
175 Command(svncommand, options).run_fatal()
177 return SvnRepository(local, options)
180 def remote_exists(cls, remote):
181 return os.system("svn list %s &> /dev/null" % remote) == 0
183 def tag_exists(self, tagname):
184 url = "%s/tags/%s" % (self.repo_root(), tagname)
185 return SvnRepository.remote_exists(url)
187 def update(self, subdir="", recursive=True):
188 path = os.path.join(self.path, subdir)
190 svncommand = "svn up %s" % path
192 svncommand = "svn up -N %s" % path
193 Command(svncommand, self.options).run_fatal()
195 def commit(self, logfile):
196 # add all new files to the repository
197 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
198 self.path, self.options).output_of()
199 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
201 def to_branch(self, branch):
202 remote = "%s/branches/%s" % (self.repo_root(), branch)
203 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
205 def to_tag(self, tag):
206 remote = "%s/tags/%s" % (self.repo_root(), branch)
207 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
209 def tag(self, tagname, logfile):
210 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
211 self_url = self.url()
212 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
214 def diff(self, f=""):
216 f = os.path.join(self.path, f)
219 return Command("svn diff %s" % f, self.options).output_of(True)
221 def diff_with_tag(self, tagname):
222 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
223 return Command("svn diff %s %s" % (tag_url, self.url()),
224 self.options).output_of(True)
226 def revert(self, f=""):
228 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
231 Command("svn revert %s -R" % self.path, self.options).run_fatal()
232 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
233 self.path, self.options).run_silent()
236 command="svn status %s" % self.path
237 return len(Command(command,self.options).output_of(True)) == 0
240 return os.path.exists(os.path.join(self.path, ".svn"))
246 def __init__(self, path, options):
248 self.options = options
251 return os.path.basename(self.path)
257 c = Command("git remote show origin", self.options)
258 out = self.__run_in_repo(c.output_of)
259 for line in out.split('\n'):
260 if line.strip().startswith("Fetch URL:"):
261 repo = line.split()[2]
264 def checkout(cls, remote, local, options, depth=1):
265 Command("rm -rf %s" % local, options).run_silent()
266 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
267 return GitRepository(local, options)
270 def remote_exists(cls, remote):
271 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
273 def tag_exists(self, tagname):
274 command = 'git tag -l | grep "^%s$"' % tagname
275 c = Command(command, self.options)
276 out = self.__run_in_repo(c.output_of, with_stderr=True)
279 def __run_in_repo(self, fun, *args, **kwargs):
282 ret = fun(*args, **kwargs)
286 def __run_command_in_repo(self, command, ignore_errors=False):
287 c = Command(command, self.options)
289 return self.__run_in_repo(c.output_of)
291 return self.__run_in_repo(c.run_fatal)
293 def update(self, subdir=None, recursive=None):
294 self.__run_command_in_repo("git fetch --tags")
295 self.__run_command_in_repo("git pull")
297 def to_branch(self, branch, remote=True):
299 branch = "origin/%s" % branch
300 return self.__run_command_in_repo("git checkout %s" % branch)
302 def to_tag(self, tag):
303 return self.__run_command_in_repo("git checkout %s" % tag)
305 def tag(self, tagname, logfile):
306 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
309 def diff(self, f=""):
310 c = Command("git diff %s" % f, self.options)
311 return self.__run_in_repo(c.output_of, with_stderr=True)
313 def diff_with_tag(self, tagname):
314 c = Command("git diff %s" % tagname, self.options)
315 return self.__run_in_repo(c.output_of, with_stderr=True)
317 def commit(self, logfile):
318 self.__run_command_in_repo("git add .", ignore_errors=True)
319 self.__run_command_in_repo("git add -u", ignore_errors=True)
320 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
321 self.__run_command_in_repo("git push")
322 self.__run_command_in_repo("git push --tags")
324 def revert(self, f=""):
326 self.__run_command_in_repo("git checkout %s" % f)
329 self.__run_command_in_repo("git --no-pager reset --hard")
330 self.__run_command_in_repo("git --no-pager clean -f")
335 s="nothing to commit (working directory clean)"
336 return Command(command, self.options).output_of(True).find(s) >= 0
337 return self.__run_in_repo(check_commit)
340 return os.path.exists(os.path.join(self.path, ".git"))
344 """ Generic repository """
345 supported_repo_types = [SvnRepository, GitRepository]
347 def __init__(self, path, options):
349 self.options = options
350 for repo in self.supported_repo_types:
351 self.repo = repo(self.path, self.options)
352 if self.repo.is_valid():
356 def has_moved_to_git(cls, module, svnpath):
357 module = git_to_svn_name(module)
358 return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (svnpath, module))
361 def remote_exists(cls, remote):
362 for repo in Repository.supported_repo_types:
363 if repo.remote_exists(remote):
367 def __getattr__(self, attr):
368 return getattr(self.repo, attr)
372 # support for tagged module is minimal, and is for the Build class only
375 svn_magic_line="--This line, and those below, will be ignored--"
376 setting_tag_format = "Setting tag %s"
378 redirectors=[ # ('module_name_varname','name'),
379 ('module_version_varname','version'),
380 ('module_taglevel_varname','taglevel'), ]
382 # where to store user's config
383 config_storage="CONFIG"
388 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
389 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
390 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
391 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
392 ("build", "Enter the name of your build module","build"),
393 ('username',"Enter your firstname and lastname for changelogs",""),
394 ("email","Enter your email address for changelogs",""),
398 def prompt_config_option(cls, key, message, default):
399 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
402 def prompt_config (cls):
403 for (key,message,default) in cls.configKeys:
405 while not cls.config[key]:
406 cls.prompt_config_option(key, message, default)
409 # for parsing module spec name:branch
410 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
411 # special form for tagged module - for Build
412 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
414 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
416 def __init__ (self,module_spec,options):
418 attempt=Module.matcher_branch_spec.match(module_spec)
420 self.name=attempt.group('name')
421 self.branch=attempt.group('branch')
423 attempt=Module.matcher_tag_spec.match(module_spec)
425 self.name=attempt.group('name')
426 self.tagname=attempt.group('tagname')
428 self.name=module_spec
430 # when available prefer to use git module name internally
431 self.name = svn_to_git_name(self.name)
434 self.module_dir="%s/%s"%(options.workdir,self.name)
435 self.repository = None
438 def run (self,command):
439 return Command(command,self.options).run()
440 def run_fatal (self,command):
441 return Command(command,self.options).run_fatal()
442 def run_prompt (self,message,fun, *args):
443 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
444 if not self.options.verbose:
446 choice=prompt(message,True,('s','how'))
450 elif choice is False:
451 print 'About to run function:', fun_msg
453 question=message+" - want to run function: " + fun_msg
454 if prompt(question,True):
457 def friendly_name (self):
458 if hasattr(self,'branch'):
459 return "%s:%s"%(self.name,self.branch)
460 elif hasattr(self,'tagname'):
461 return "%s@%s"%(self.name,self.tagname)
466 def git_remote_dir (cls, name):
467 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
470 def svn_remote_dir (cls, name):
471 name = git_to_svn_name(name)
472 svn = cls.config['svnpath']
473 if svn.endswith('/'):
474 return "%s%s" % (svn, name)
475 return "%s/%s" % (svn, name)
477 def svn_selected_remote(self):
478 svn_name = git_to_svn_name(self.name)
479 remote = self.svn_remote_dir(svn_name)
480 if hasattr(self,'branch'):
481 remote = "%s/branches/%s" % (remote, self.branch)
482 elif hasattr(self,'tagname'):
483 remote = "%s/tags/%s" % (remote, self.tagname)
485 remote = "%s/trunk" % remote
490 def init_homedir (cls, options):
491 if options.verbose and options.mode not in Main.silent_modes:
492 print 'Checking for', options.workdir
493 storage="%s/%s"%(options.workdir, cls.config_storage)
494 # sanity check. Either the topdir exists AND we have a config/storage
495 # or topdir does not exist and we create it
496 # to avoid people use their own daily svn repo
497 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
498 print """The directory %s exists and has no CONFIG file
499 If this is your regular working directory, please provide another one as the
500 module-* commands need a fresh working dir. Make sure that you do not use
501 that for other purposes than tagging""" % options.workdir
504 def checkout_build():
505 print "Checking out build module..."
506 remote = cls.git_remote_dir(cls.config['build'])
507 local = os.path.join(options.workdir, cls.config['build'])
508 GitRepository.checkout(remote, local, options, depth=1)
513 for (key,message,default) in Module.configKeys:
514 f.write("%s=%s\n"%(key,Module.config[key]))
517 print 'Stored',storage
518 Command("cat %s"%storage,options).run()
523 for line in f.readlines():
524 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
525 Module.config[key]=value
528 if not os.path.isdir (options.workdir):
529 print "Cannot find",options.workdir,"let's create it"
530 Command("mkdir -p %s" % options.workdir, options).run_silent()
536 # check missing config options
538 for (key,message,default) in cls.configKeys:
539 if not Module.config.has_key(key):
540 print "Configuration changed for module-tools"
541 cls.prompt_config_option(key, message, default)
545 Command("rm -rf %s" % options.workdir, options).run_silent()
546 Command("mkdir -p %s" % options.workdir, options).run_silent()
550 build_dir = os.path.join(options.workdir, cls.config['build'])
551 if not os.path.isdir(build_dir):
554 build = Repository(build_dir, options)
555 if not build.is_clean():
556 print "build module needs a revert"
561 if options.verbose and options.mode not in Main.silent_modes:
562 print '******** Using config'
563 for (key,message,default) in Module.configKeys:
564 print '\t',key,'=',Module.config[key]
566 def init_module_dir (self):
567 if self.options.verbose:
568 print 'Checking for',self.module_dir
570 if not os.path.isdir (self.module_dir):
571 if Repository.has_moved_to_git(self.name, Module.config['svnpath']):
572 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
576 remote = self.svn_selected_remote()
577 self.repository = SvnRepository.checkout(remote,
579 self.options, recursive=False)
581 self.repository = Repository(self.module_dir, self.options)
582 if self.repository.type == "svn":
583 # check if module has moved to git
584 if Repository.has_moved_to_git(self.name, Module.config['svnpath']):
585 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
586 self.init_module_dir()
587 # check if we have the required branch/tag
588 if self.repository.url() != self.svn_selected_remote():
589 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
590 self.init_module_dir()
592 elif self.repository.type == "git":
593 if hasattr(self,'branch'):
594 self.repository.to_branch(self.branch)
595 elif hasattr(self,'tagname'):
596 self.repository.to_tag(self.tagname)
599 raise Exception, 'Cannot find %s - check module name'%self.module_dir
602 def revert_module_dir (self):
603 if self.options.fast_checks:
604 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
606 if self.options.verbose:
607 print 'Checking whether', self.module_dir, 'needs being reverted'
609 if not self.repository.is_clean():
610 self.repository.revert()
612 def update_module_dir (self):
613 if self.options.fast_checks:
614 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
616 if self.options.verbose:
617 print 'Updating', self.module_dir
618 self.repository.update()
620 def main_specname (self):
621 attempt="%s/%s.spec"%(self.module_dir,self.name)
622 if os.path.isfile (attempt):
624 pattern1="%s/*.spec"%self.module_dir
625 level1=glob(pattern1)
628 pattern2="%s/*/*.spec"%self.module_dir
629 level2=glob(pattern2)
633 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
635 def all_specnames (self):
636 level1=glob("%s/*.spec" % self.module_dir)
637 if level1: return level1
638 level2=glob("%s/*/*.spec" % self.module_dir)
641 def parse_spec (self, specfile, varnames):
642 if self.options.verbose:
643 print 'Parsing',specfile,
649 for line in f.readlines():
650 attempt=Module.matcher_rpm_define.match(line)
652 (define,var,value)=attempt.groups()
656 if self.options.debug:
657 print 'found',len(result),'keys'
658 for (k,v) in result.iteritems():
662 # stores in self.module_name_varname the rpm variable to be used for the module's name
663 # and the list of these names in self.varnames
664 def spec_dict (self):
665 specfile=self.main_specname()
666 redirector_keys = [ varname for (varname,default) in Module.redirectors]
667 redirect_dict = self.parse_spec(specfile,redirector_keys)
668 if self.options.debug:
669 print '1st pass parsing done, redirect_dict=',redirect_dict
671 for (varname,default) in Module.redirectors:
672 if redirect_dict.has_key(varname):
673 setattr(self,varname,redirect_dict[varname])
674 varnames += [redirect_dict[varname]]
676 setattr(self,varname,default)
677 varnames += [ default ]
678 self.varnames = varnames
679 result = self.parse_spec (specfile,self.varnames)
680 if self.options.debug:
681 print '2st pass parsing done, varnames=',varnames,'result=',result
684 def patch_spec_var (self, patch_dict,define_missing=False):
685 for specfile in self.all_specnames():
686 # record the keys that were changed
687 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
688 newspecfile=specfile+".new"
689 if self.options.verbose:
690 print 'Patching',specfile,'for',patch_dict.keys()
692 new=open(newspecfile,"w")
694 for line in spec.readlines():
695 attempt=Module.matcher_rpm_define.match(line)
697 (define,var,value)=attempt.groups()
698 if var in patch_dict.keys():
699 if self.options.debug:
700 print 'rewriting %s as %s'%(var,patch_dict[var])
701 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
706 for (key,was_changed) in changed.iteritems():
708 if self.options.debug:
709 print 'rewriting missing %s as %s'%(key,patch_dict[key])
710 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
713 os.rename(newspecfile,specfile)
715 # returns all lines until the magic line
716 def unignored_lines (self, logfile):
718 white_line_matcher = re.compile("\A\s*\Z")
719 for logline in file(logfile).readlines():
720 if logline.strip() == Module.svn_magic_line:
722 elif white_line_matcher.match(logline):
725 result.append(logline.strip()+'\n')
728 # creates a copy of the input with only the unignored lines
729 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
731 f.write(self.setting_tag_format%new_tag_name + '\n')
732 for line in self.unignored_lines(filein):
736 def insert_changelog (self, logfile, oldtag, newtag):
737 for specfile in self.all_specnames():
738 newspecfile=specfile+".new"
739 if self.options.verbose:
740 print 'Inserting changelog from %s into %s'%(logfile,specfile)
742 new=open(newspecfile,"w")
743 for line in spec.readlines():
745 if re.compile('%changelog').match(line):
746 dateformat="* %a %b %d %Y"
747 datepart=time.strftime(dateformat)
748 logpart="%s <%s> - %s"%(Module.config['username'],
749 Module.config['email'],
751 new.write(datepart+" "+logpart+"\n")
752 for logline in self.unignored_lines(logfile):
753 new.write("- " + logline)
757 os.rename(newspecfile,specfile)
759 def show_dict (self, spec_dict):
760 if self.options.verbose:
761 for (k,v) in spec_dict.iteritems():
764 def last_tag (self, spec_dict):
766 return "%s-%s" % (spec_dict[self.module_version_varname],
767 spec_dict[self.module_taglevel_varname])
769 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
771 def tag_name (self, spec_dict, old_svn_name=False):
772 base_tag_name = self.name
774 base_tag_name = git_to_svn_name(self.name)
775 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
778 ##############################
779 # using fine_grain means replacing only those instances that currently refer to this tag
780 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
781 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
782 newtagsfile=tagsfile+".new"
784 new=open(newtagsfile,"w")
787 # fine-grain : replace those lines that refer to oldname
789 if self.options.verbose:
790 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
791 matcher=re.compile("^(.*)%s(.*)"%oldname)
792 for line in tags.readlines():
793 if not matcher.match(line):
796 (begin,end)=matcher.match(line).groups()
797 new.write(begin+newname+end+"\n")
799 # brute-force : change uncommented lines that define <module>-SVNPATH
801 if self.options.verbose:
802 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
803 pattern="\A\s*(?P<make_name>[^\s]+)-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
805 matcher_module=re.compile(pattern)
806 for line in tags.readlines():
807 attempt=matcher_module.match(line)
809 if line.find("-GITPATH") >= 0:
810 modulepath = "%s-GITPATH"%(attempt.group('make_name'))
811 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
813 moduleath="%s-SVNPATH"%(attempt.group('make_name'))
814 replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
815 if self.options.verbose:
816 print ' ' + modulepath,
817 new.write(replacement)
823 os.rename(newtagsfile,tagsfile)
824 if self.options.verbose: print "%d changes"%matches
827 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
828 if self.options.verbose:
829 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
831 found_tagname = tagname
832 found = self.repository.tag_exists(tagname)
833 if not found and old_svn_tag_name:
834 if self.options.verbose:
836 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
837 found = self.repository.tag_exists(old_svn_tag_name)
839 found_tagname = old_svn_tag_name
841 if (found and need_it) or (not found and not need_it):
842 if self.options.verbose:
844 if found: print "- found"
845 else: print "- not found"
847 if self.options.verbose:
850 raise Exception, "tag (%s) is already there" % tagname
852 raise Exception, "can not find required tag (%s)" % tagname
857 ##############################
859 self.init_module_dir()
860 self.revert_module_dir()
861 self.update_module_dir()
863 spec_dict = self.spec_dict()
864 self.show_dict(spec_dict)
867 old_tag_name = self.tag_name(spec_dict)
868 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
870 if (self.options.new_version):
871 # new version set on command line
872 spec_dict[self.module_version_varname] = self.options.new_version
873 spec_dict[self.module_taglevel_varname] = 0
876 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
877 spec_dict[self.module_taglevel_varname] = new_taglevel
879 new_tag_name = self.tag_name(spec_dict)
882 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
883 new_tag_name = self.check_tag(new_tag_name, need_it=False)
886 diff_output = self.repository.diff_with_tag(old_tag_name)
887 if len(diff_output) == 0:
888 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
891 # side effect in trunk's specfile
892 self.patch_spec_var(spec_dict)
894 # prepare changelog file
895 # we use the standard subversion magic string (see svn_magic_line)
896 # so we can provide useful information, such as version numbers and diff
898 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
899 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
900 setting_tag_line=Module.setting_tag_format%new_tag_name
901 file(changelog,"w").write("""
904 Please write a changelog for this new tag in the section above
905 """%(Module.svn_magic_line,setting_tag_line))
907 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
908 file(changelog,"a").write('DIFF=========\n' + diff_output)
910 if self.options.debug:
914 self.run("%s %s"%(self.options.editor,changelog))
915 # strip magic line in second file - looks like svn has changed its magic line with 1.6
916 # so we do the job ourselves
917 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
918 # insert changelog in spec
919 if self.options.changelog:
920 self.insert_changelog (changelog,old_tag_name,new_tag_name)
923 build_path = os.path.join(self.options.workdir,
924 Module.config['build'])
925 build = Repository(build_path, self.options)
926 if self.options.build_branch:
927 build.to_branch(self.options.build_branch)
928 if not build.is_clean():
931 tagsfiles=glob(build.path+"/*-tags*.mk")
932 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
936 for tagsfile in tagsfiles:
937 status=tagsdict[tagsfile]
938 basename=os.path.basename(tagsfile)
939 print ".................... Dealing with %s"%basename
940 while tagsdict[tagsfile] == 'todo' :
941 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
942 [ ('y','es'), ('n', 'ext'), ('f','orce'),
943 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
946 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
948 print 'Done with %s'%os.path.basename(tagsfile)
949 tagsdict[tagsfile]='done'
951 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
953 print build.diff(f=tagsfile)
955 build.revert(f=tagsfile)
957 self.run("cat %s"%tagsfile)
960 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
961 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
962 d: show current diff for this tag file
963 r: revert that tag file
964 c: cat the current tag file
965 n: move to next file"""%locals()
967 if prompt("Want to review changes on tags files",False):
968 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
973 def diff_all_changes():
975 print self.repository.diff()
977 def commit_all_changes(log):
978 self.repository.commit(log)
981 self.run_prompt("Review module and build", diff_all_changes)
982 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
983 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
985 if self.options.debug:
986 print 'Preserving',changelog,'and stripped',changelog_svn
989 os.unlink(changelog_svn)
992 ##############################
993 def do_version (self):
994 self.init_module_dir()
995 self.revert_module_dir()
996 self.update_module_dir()
997 spec_dict = self.spec_dict()
999 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1000 self.last_tag(spec_dict)))
1001 for varname in self.varnames:
1002 if not spec_dict.has_key(varname):
1003 self.html_print ('Could not find %%define for %s'%varname)
1006 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1007 if self.options.verbose:
1008 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1009 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1010 self.html_print_end()
1013 ##############################
1015 self.init_module_dir()
1016 self.revert_module_dir()
1017 self.update_module_dir()
1018 spec_dict = self.spec_dict()
1019 self.show_dict(spec_dict)
1022 tag_name = self.tag_name(spec_dict)
1023 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1026 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1028 if self.options.verbose:
1029 print 'Getting diff'
1030 diff_output = self.repository.diff_with_tag(tag_name)
1032 if self.options.list:
1036 thename=self.friendly_name()
1038 if self.options.www and diff_output:
1039 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1040 thename,self.last_tag(spec_dict),len(diff_output)))
1042 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1043 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1044 self.html_store_pre (diff_output)
1045 elif not self.options.www:
1046 print 'x'*30,'module',thename
1047 print 'x'*20,'<',tag_name
1048 print 'x'*20,'>',thename
1051 ##############################
1052 # store and restitute html fragments
1054 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1057 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1060 def html_quote (text):
1061 return text.replace('&','&').replace('<','<').replace('>','>')
1063 # only the fake error module has multiple titles
1064 def html_store_title (self, title):
1065 if not hasattr(self,'titles'): self.titles=[]
1066 self.titles.append(title)
1068 def html_store_raw (self, html):
1069 if not hasattr(self,'body'): self.body=''
1072 def html_store_pre (self, text):
1073 if not hasattr(self,'body'): self.body=''
1074 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1076 def html_print (self, txt):
1077 if not self.options.www:
1080 if not hasattr(self,'in_list') or not self.in_list:
1081 self.html_store_raw('<ul>')
1083 self.html_store_raw('<li>'+txt+'</li>')
1085 def html_print_end (self):
1086 if self.options.www:
1087 self.html_store_raw ('</ul>')
1090 def html_dump_header(title):
1091 nowdate=time.strftime("%Y-%m-%d")
1092 nowtime=time.strftime("%H:%M (%Z)")
1093 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1094 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1097 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1098 <style type="text/css">
1099 body { font-family:georgia, serif; }
1100 h1 {font-size: large; }
1101 p.title {font-size: x-large; }
1102 span.error {text-weight:bold; color: red; }
1106 <p class='title'> %s - status on %s at %s</p>
1108 """%(title,title,nowdate,nowtime)
1111 def html_dump_middle():
1115 def html_dump_footer():
1116 print "</body></html"
1118 def html_dump_toc(self):
1119 if hasattr(self,'titles'):
1120 for title in self.titles:
1121 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1123 def html_dump_body(self):
1124 if hasattr(self,'titles'):
1125 for title in self.titles:
1126 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1127 if hasattr(self,'body'):
1129 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1132 ##############################
1135 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1137 module-tools : a set of tools to manage subversion tags and specfile
1138 requires the specfile to either
1139 * define *version* and *taglevel*
1141 * define redirection variables module_version_varname / module_taglevel_varname
1143 by default, the trunk of modules is taken into account
1144 in this case, just mention the module name as <module_desc>
1146 if you wish to work on a branch rather than on the trunk,
1147 you can use something like e.g. Mom:2.1 as <module_desc>
1149 release_usage="""Usage: %prog [options] tag1 .. tagn
1150 Extract release notes from the changes in specfiles between several build tags, latest first
1152 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1153 You can refer to a (build) branch by prepending a colon, like in
1154 release-changelog :4.2 4.2-rc25
1155 You can refer to the build trunk by just mentioning 'trunk', e.g.
1156 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1158 common_usage="""More help:
1159 see http://svn.planet-lab.org/wiki/ModuleTools"""
1162 'list' : "displays a list of available tags or branches",
1163 'version' : "check latest specfile and print out details",
1164 'diff' : "show difference between module (trunk or branch) and latest tag",
1165 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1166 create new tag and and monitor its adoption in build/*-tags*.mk""",
1167 'branch' : """create a branch for this module, from the latest tag on the trunk,
1168 and change trunk's version number to reflect the new branch name;
1169 you can specify the new branch name by using module:branch""",
1170 'sync' : """create a tag from the module
1171 this is a last resort option, mostly for repairs""",
1172 'changelog' : """extract changelog between build tags
1173 expected arguments are a list of tags""",
1176 silent_modes = ['list']
1177 release_modes = ['changelog']
1180 def optparse_list (option, opt, value, parser):
1182 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1184 setattr(parser.values,option.dest,value.split())
1189 for function in Main.modes.keys():
1190 if sys.argv[0].find(function) >= 0:
1194 print "Unsupported command",sys.argv[0]
1195 print "Supported commands:" + " ".join(Main.modes.keys())
1198 if mode not in Main.release_modes:
1199 usage = Main.module_usage
1200 usage += Main.common_usage
1201 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1203 usage = Main.release_usage
1204 usage += Main.common_usage
1206 parser=OptionParser(usage=usage)
1208 if mode == "tag" or mode == 'branch':
1209 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1210 help="set new version and reset taglevel to 0")
1212 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1213 help="do not update changelog section in specfile when tagging")
1214 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1215 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1216 if mode == "tag" or mode == "sync" :
1217 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1218 help="specify editor")
1220 if mode in ["diff","version"] :
1221 parser.add_option("-W","--www", action="store", dest="www", default=False,
1222 help="export diff in html format, e.g. -W trunk")
1225 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1226 help="just list modules that exhibit differences")
1228 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1229 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1230 help="run on all modules as found in %s"%default_modules_list)
1231 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1232 help="run on all modules found in specified file")
1233 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1234 help="dry run - shell commands are only displayed")
1235 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1236 default=[], nargs=1,type="string",
1237 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1238 -- can be set multiple times, or use quotes""")
1240 parser.add_option("-w","--workdir", action="store", dest="workdir",
1241 default="%s/%s"%(os.getenv("HOME"),"modules"),
1242 help="""name for dedicated working dir - defaults to ~/modules
1243 ** THIS MUST NOT ** be your usual working directory""")
1244 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1245 help="skip safety checks, such as svn updates -- use with care")
1247 # default verbosity depending on function - temp
1248 verbose_modes= ['tag', 'sync', 'branch']
1250 if mode not in verbose_modes:
1251 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1252 help="run in verbose mode")
1254 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1255 help="run in quiet (non-verbose) mode")
1256 (options, args) = parser.parse_args()
1258 if not hasattr(options,'dry_run'):
1259 options.dry_run=False
1260 if not hasattr(options,'www'):
1266 if options.all_modules:
1267 options.modules_list=default_modules_list
1268 if options.modules_list:
1269 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1273 Module.init_homedir(options)
1276 modules=[ Module(modname,options) for modname in args ]
1277 # hack: create a dummy Module to store errors/warnings
1278 error_module = Module('__errors__',options)
1280 for module in modules:
1281 if len(args)>1 and mode not in Main.silent_modes:
1283 print '========================================',module.friendly_name()
1284 # call the method called do_<mode>
1285 method=Module.__dict__["do_%s"%mode]
1290 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1291 (module.friendly_name(), str(e))
1292 error_module.html_store_title(title)
1295 traceback.print_exc()
1296 print 'Skipping module %s: '%modname,e
1300 modetitle="Changes to tag in %s"%options.www
1301 elif mode == "version":
1302 modetitle="Latest tags in %s"%options.www
1303 modules.append(error_module)
1304 error_module.html_dump_header(modetitle)
1305 for module in modules:
1306 module.html_dump_toc()
1307 Module.html_dump_middle()
1308 for module in modules:
1309 module.html_dump_body()
1310 Module.html_dump_footer()
1312 ####################
1313 if __name__ == "__main__" :
1316 except KeyboardInterrupt: