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 = {
16 "BootManager": "bootmanager",
18 "VserverReference": "vserver-reference",
19 "BootstrapFS": "bootstrapfs",
22 "NodeManager": "nodemanager",
23 "NodeUpdate": "nodeupdate"
26 def svn_to_git_name(module):
27 if RENAMED_SVN_MODULES.has_key(module):
28 return RENAMED_SVN_MODULES[module]
31 def git_to_svn_name(module):
32 for key in RENAMED_SVN_MODULES:
33 if module == RENAMED_SVN_MODULES[key]:
38 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase
39 def prompt (question,default=True,other_choices=[],allow_outside=False):
40 if not isinstance (other_choices,list):
41 other_choices = [ other_choices ]
42 chars = [ c for (c,rest) in other_choices ]
46 if default is True: choices.append('[y]')
47 else : choices.append('y')
49 if default is False: choices.append('[n]')
50 else : choices.append('n')
52 for (char,choice) in other_choices:
54 choices.append("["+char+"]"+choice)
56 choices.append("<"+char+">"+choice)
58 answer=raw_input(question + " " + "/".join(choices) + " ? ")
61 answer=answer[0].lower()
63 if 'y' in chars: return 'y'
66 if 'n' in chars: return 'n'
69 for (char,choice) in other_choices:
74 return prompt(question,default,other_choices)
80 editor = os.environ['EDITOR']
88 def print_fold (line):
89 while len(line) >= fold_length:
90 print line[:fold_length],'\\'
91 line=line[fold_length:]
95 def __init__ (self,command,options):
98 self.tmp="/tmp/command-%d"%os.getpid()
101 if self.options.dry_run:
102 print 'dry_run',self.command
104 if self.options.verbose and self.options.mode not in Main.silent_modes:
105 print '+',self.command
107 return os.system(self.command)
109 def run_silent (self):
110 if self.options.dry_run:
111 print 'dry_run',self.command
113 if self.options.verbose:
114 print '+',self.command,' .. ',
116 retcod=os.system(self.command + " &> " + self.tmp)
118 print "FAILED ! -- out+err below (command was %s)"%self.command
119 os.system("cat " + self.tmp)
120 print "FAILED ! -- end of quoted output"
121 elif self.options.verbose:
127 if self.run_silent() !=0:
128 raise Exception,"Command %s failed"%self.command
130 # returns stdout, like bash's $(mycommand)
131 def output_of (self,with_stderr=False):
132 if self.options.dry_run:
133 print 'dry_run',self.command
134 return 'dry_run output'
135 tmp="/tmp/status-%d"%os.getpid()
136 if self.options.debug:
137 print '+',self.command,' .. ',
146 result=file(tmp).read()
148 if self.options.debug:
156 def __init__(self, path, options):
158 self.options = options
161 return os.path.basename(self.path)
164 out = Command("svn info %s" % self.path, self.options).output_of()
165 for line in out.split('\n'):
166 if line.startswith("URL:"):
167 return line.split()[1].strip()
170 out = Command("svn info %s" % self.path, self.options).output_of()
171 for line in out.split('\n'):
172 if line.startswith("Repository Root:"):
173 root = line.split()[2].strip()
174 return "%s/%s" % (root, self.name())
177 def checkout(cls, remote, local, options, recursive=False):
179 svncommand = "svn co %s %s" % (remote, local)
181 svncommand = "svn co -N %s %s" % (remote, local)
182 Command("rm -rf %s" % local, options).run_silent()
183 Command(svncommand, options).run_fatal()
185 return SvnRepository(local, options)
188 def remote_exists(cls, remote):
189 return os.system("svn list %s &> /dev/null" % remote) == 0
191 def tag_exists(self, tagname):
192 url = "%s/tags/%s" % (self.repo_root(), tagname)
193 return SvnRepository.remote_exists(url)
195 def update(self, subdir="", recursive=True, branch=None):
196 path = os.path.join(self.path, subdir)
198 svncommand = "svn up %s" % path
200 svncommand = "svn up -N %s" % path
201 Command(svncommand, self.options).run_fatal()
203 def commit(self, logfile):
204 # add all new files to the repository
205 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
206 self.path, self.options).output_of()
207 Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
209 def to_branch(self, branch):
210 remote = "%s/branches/%s" % (self.repo_root(), branch)
211 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
213 def to_tag(self, tag):
214 remote = "%s/tags/%s" % (self.repo_root(), branch)
215 SvnRepository.checkout(remote, self.path, self.options, recursive=True)
217 def tag(self, tagname, logfile):
218 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
219 self_url = self.url()
220 Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
222 def diff(self, f=""):
224 f = os.path.join(self.path, f)
227 return Command("svn diff %s" % f, self.options).output_of(True)
229 def diff_with_tag(self, tagname):
230 tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
231 return Command("svn diff %s %s" % (tag_url, self.url()),
232 self.options).output_of(True)
234 def revert(self, f=""):
236 Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
239 Command("svn revert %s -R" % self.path, self.options).run_fatal()
240 Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
241 self.path, self.options).run_silent()
244 command="svn status %s" % self.path
245 return len(Command(command,self.options).output_of(True)) == 0
248 return os.path.exists(os.path.join(self.path, ".svn"))
254 def __init__(self, path, options):
256 self.options = options
259 return os.path.basename(self.path)
262 return self.repo_root()
265 c = Command("git remote show origin", self.options)
266 out = self.__run_in_repo(c.output_of)
267 for line in out.split('\n'):
268 if line.strip().startswith("Fetch URL:"):
269 return line.split()[2]
272 def checkout(cls, remote, local, options, depth=0):
273 Command("rm -rf %s" % local, options).run_silent()
274 Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
275 return GitRepository(local, options)
278 def remote_exists(cls, remote):
279 return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
281 def tag_exists(self, tagname):
282 command = 'git tag -l | grep "^%s$"' % tagname
283 c = Command(command, self.options)
284 out = self.__run_in_repo(c.output_of, with_stderr=True)
287 def __run_in_repo(self, fun, *args, **kwargs):
290 ret = fun(*args, **kwargs)
294 def __run_command_in_repo(self, command, ignore_errors=False):
295 c = Command(command, self.options)
297 return self.__run_in_repo(c.output_of)
299 return self.__run_in_repo(c.run_fatal)
301 def __is_commit_id(self, id):
302 c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
303 ret = self.__run_in_repo(c.output_of, with_stderr=False)
304 if ret.strip() == id:
308 def update(self, subdir=None, recursive=None, branch="master"):
309 if branch == "master":
310 self.__run_command_in_repo("git checkout %s" % branch)
312 self.to_branch(branch, remote=True)
313 self.__run_command_in_repo("git fetch origin --tags")
314 self.__run_command_in_repo("git fetch origin")
315 if not self.__is_commit_id(branch):
316 # we don't need to merge anythign for commit ids.
317 self.__run_command_in_repo("git merge --ff origin/%s" % branch)
319 def to_branch(self, branch, remote=True):
322 command = "git branch --track %s origin/%s" % (branch, branch)
323 c = Command(command, self.options)
324 self.__run_in_repo(c.output_of, with_stderr=True)
325 return self.__run_command_in_repo("git checkout %s" % branch)
327 def to_tag(self, tag):
329 return self.__run_command_in_repo("git checkout %s" % tag)
331 def tag(self, tagname, logfile):
332 self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
335 def diff(self, f=""):
336 c = Command("git diff %s" % f, self.options)
337 return self.__run_in_repo(c.output_of, with_stderr=True)
339 def diff_with_tag(self, tagname):
340 c = Command("git diff %s" % tagname, self.options)
341 return self.__run_in_repo(c.output_of, with_stderr=True)
343 def commit(self, logfile, branch="master"):
344 self.__run_command_in_repo("git add .", ignore_errors=True)
345 self.__run_command_in_repo("git add -u", ignore_errors=True)
346 self.__run_command_in_repo("git commit -F %s" % logfile, ignore_errors=True)
347 if branch == "master" or self.__is_commit_id(branch):
348 self.__run_command_in_repo("git push")
350 self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
351 self.__run_command_in_repo("git push --tags")
353 def revert(self, f=""):
355 self.__run_command_in_repo("git checkout %s" % f)
358 self.__run_command_in_repo("git --no-pager reset --hard")
359 self.__run_command_in_repo("git --no-pager clean -f")
364 s="nothing to commit (working directory clean)"
365 return Command(command, self.options).output_of(True).find(s) >= 0
366 return self.__run_in_repo(check_commit)
369 return os.path.exists(os.path.join(self.path, ".git"))
373 """ Generic repository """
374 supported_repo_types = [SvnRepository, GitRepository]
376 def __init__(self, path, options):
378 self.options = options
379 for repo in self.supported_repo_types:
380 self.repo = repo(self.path, self.options)
381 if self.repo.is_valid():
385 def has_moved_to_git(cls, module, config):
386 module = svn_to_git_name(module)
387 # check if the module is already in Git
388 # return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
389 return GitRepository.remote_exists(Module.git_remote_dir(module))
393 def remote_exists(cls, remote):
394 for repo in Repository.supported_repo_types:
395 if repo.remote_exists(remote):
399 def __getattr__(self, attr):
400 return getattr(self.repo, attr)
404 # support for tagged module is minimal, and is for the Build class only
407 svn_magic_line="--This line, and those below, will be ignored--"
408 setting_tag_format = "Setting tag %s"
410 redirectors=[ # ('module_name_varname','name'),
411 ('module_version_varname','version'),
412 ('module_taglevel_varname','taglevel'), ]
414 # where to store user's config
415 config_storage="CONFIG"
420 configKeys=[ ('svnpath',"Enter your toplevel svnpath",
421 "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
422 ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
423 ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
424 ("build", "Enter the name of your build module","build"),
425 ('username',"Enter your firstname and lastname for changelogs",""),
426 ("email","Enter your email address for changelogs",""),
430 def prompt_config_option(cls, key, message, default):
431 cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
434 def prompt_config (cls):
435 for (key,message,default) in cls.configKeys:
437 while not cls.config[key]:
438 cls.prompt_config_option(key, message, default)
440 # for parsing module spec name:branch
441 matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
442 # special form for tagged module - for Build
443 matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
445 matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
448 def parse_module_spec(cls, module_spec):
449 name = branch_or_tagname = module_type = ""
451 attempt=Module.matcher_branch_spec.match(module_spec)
453 module_type = "branch"
454 name=attempt.group('name')
455 branch_or_tagname=attempt.group('branch')
457 attempt=Module.matcher_tag_spec.match(module_spec)
460 name=attempt.group('name')
461 branch_or_tagname=attempt.group('tagname')
464 return name, branch_or_tagname, module_type
467 def __init__ (self,module_spec,options):
469 self.name, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
471 if module_type == "branch":
472 self.branch=branch_or_tagname
473 elif module_type == "tag":
474 self.tagname=branch_or_tagname
476 # when available prefer to use git module name internally
477 self.name = svn_to_git_name(self.name)
480 self.module_dir="%s/%s"%(options.workdir,self.name)
481 self.repository = None
484 def run (self,command):
485 return Command(command,self.options).run()
486 def run_fatal (self,command):
487 return Command(command,self.options).run_fatal()
488 def run_prompt (self,message,fun, *args):
489 fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
490 if not self.options.verbose:
492 choice=prompt(message,True,('s','how'))
496 elif choice is False:
497 print 'About to run function:', fun_msg
499 question=message+" - want to run function: " + fun_msg
500 if prompt(question,True):
503 def friendly_name (self):
504 if hasattr(self,'branch'):
505 return "%s:%s"%(self.name,self.branch)
506 elif hasattr(self,'tagname'):
507 return "%s@%s"%(self.name,self.tagname)
512 def git_remote_dir (cls, name):
513 return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
516 def svn_remote_dir (cls, name):
517 name = git_to_svn_name(name)
518 svn = cls.config['svnpath']
519 if svn.endswith('/'):
520 return "%s%s" % (svn, name)
521 return "%s/%s" % (svn, name)
523 def svn_selected_remote(self):
524 svn_name = git_to_svn_name(self.name)
525 remote = self.svn_remote_dir(svn_name)
526 if hasattr(self,'branch'):
527 remote = "%s/branches/%s" % (remote, self.branch)
528 elif hasattr(self,'tagname'):
529 remote = "%s/tags/%s" % (remote, self.tagname)
531 remote = "%s/trunk" % remote
536 def init_homedir (cls, options):
537 if options.verbose and options.mode not in Main.silent_modes:
538 print 'Checking for', options.workdir
539 storage="%s/%s"%(options.workdir, cls.config_storage)
540 # sanity check. Either the topdir exists AND we have a config/storage
541 # or topdir does not exist and we create it
542 # to avoid people use their own daily svn repo
543 if os.path.isdir(options.workdir) and not os.path.isfile(storage):
544 print """The directory %s exists and has no CONFIG file
545 If this is your regular working directory, please provide another one as the
546 module-* commands need a fresh working dir. Make sure that you do not use
547 that for other purposes than tagging""" % options.workdir
550 def checkout_build():
551 print "Checking out build module..."
552 remote = cls.git_remote_dir(cls.config['build'])
553 local = os.path.join(options.workdir, cls.config['build'])
554 GitRepository.checkout(remote, local, options, depth=1)
559 for (key,message,default) in Module.configKeys:
560 f.write("%s=%s\n"%(key,Module.config[key]))
563 print 'Stored',storage
564 Command("cat %s"%storage,options).run()
569 for line in f.readlines():
570 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
571 Module.config[key]=value
574 if not os.path.isdir (options.workdir):
575 print "Cannot find",options.workdir,"let's create it"
576 Command("mkdir -p %s" % options.workdir, options).run_silent()
582 # check missing config options
584 for (key,message,default) in cls.configKeys:
585 if not Module.config.has_key(key):
586 print "Configuration changed for module-tools"
587 cls.prompt_config_option(key, message, default)
591 Command("rm -rf %s" % options.workdir, options).run_silent()
592 Command("mkdir -p %s" % options.workdir, options).run_silent()
596 build_dir = os.path.join(options.workdir, cls.config['build'])
597 if not os.path.isdir(build_dir):
600 build = Repository(build_dir, options)
601 if not build.is_clean():
602 print "build module needs a revert"
607 if options.verbose and options.mode not in Main.silent_modes:
608 print '******** Using config'
609 for (key,message,default) in Module.configKeys:
610 print '\t',key,'=',Module.config[key]
612 def init_module_dir (self):
613 if self.options.verbose:
614 print 'Checking for',self.module_dir
616 if not os.path.isdir (self.module_dir):
617 if Repository.has_moved_to_git(self.name, Module.config):
618 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
622 remote = self.svn_selected_remote()
623 self.repository = SvnRepository.checkout(remote,
625 self.options, recursive=False)
627 self.repository = Repository(self.module_dir, self.options)
628 if self.repository.type == "svn":
629 # check if module has moved to git
630 if Repository.has_moved_to_git(self.name, Module.config):
631 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
632 self.init_module_dir()
633 # check if we have the required branch/tag
634 if self.repository.url() != self.svn_selected_remote():
635 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
636 self.init_module_dir()
638 elif self.repository.type == "git":
639 if hasattr(self,'branch'):
640 print "to branch", self.branch
641 self.repository.to_branch(self.branch)
642 elif hasattr(self,'tagname'):
643 print "to tag", self.tagname
644 self.repository.to_tag(self.tagname)
647 raise Exception, 'Cannot find %s - check module name'%self.module_dir
650 def revert_module_dir (self):
651 if self.options.fast_checks:
652 if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
654 if self.options.verbose:
655 print 'Checking whether', self.module_dir, 'needs being reverted'
657 if not self.repository.is_clean():
658 self.repository.revert()
660 def update_module_dir (self):
661 if self.options.fast_checks:
662 if self.options.verbose: print 'Skipping update of %s' % self.module_dir
664 if self.options.verbose:
665 print 'Updating', self.module_dir
667 if hasattr(self,'branch'):
668 self.repository.update(branch=self.branch)
669 elif hasattr(self,'tagname'):
670 self.repository.update(branch=self.tagname)
672 self.repository.update()
674 def main_specname (self):
675 attempt="%s/%s.spec"%(self.module_dir,self.name)
676 if os.path.isfile (attempt):
678 pattern1="%s/*.spec"%self.module_dir
679 level1=glob(pattern1)
682 pattern2="%s/*/*.spec"%self.module_dir
683 level2=glob(pattern2)
687 raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
689 def all_specnames (self):
690 level1=glob("%s/*.spec" % self.module_dir)
691 if level1: return level1
692 level2=glob("%s/*/*.spec" % self.module_dir)
695 def parse_spec (self, specfile, varnames):
696 if self.options.verbose:
697 print 'Parsing',specfile,
703 for line in f.readlines():
704 attempt=Module.matcher_rpm_define.match(line)
706 (define,var,value)=attempt.groups()
710 if self.options.debug:
711 print 'found',len(result),'keys'
712 for (k,v) in result.iteritems():
716 # stores in self.module_name_varname the rpm variable to be used for the module's name
717 # and the list of these names in self.varnames
718 def spec_dict (self):
719 specfile=self.main_specname()
720 redirector_keys = [ varname for (varname,default) in Module.redirectors]
721 redirect_dict = self.parse_spec(specfile,redirector_keys)
722 if self.options.debug:
723 print '1st pass parsing done, redirect_dict=',redirect_dict
725 for (varname,default) in Module.redirectors:
726 if redirect_dict.has_key(varname):
727 setattr(self,varname,redirect_dict[varname])
728 varnames += [redirect_dict[varname]]
730 setattr(self,varname,default)
731 varnames += [ default ]
732 self.varnames = varnames
733 result = self.parse_spec (specfile,self.varnames)
734 if self.options.debug:
735 print '2st pass parsing done, varnames=',varnames,'result=',result
738 def patch_spec_var (self, patch_dict,define_missing=False):
739 for specfile in self.all_specnames():
740 # record the keys that were changed
741 changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
742 newspecfile=specfile+".new"
743 if self.options.verbose:
744 print 'Patching',specfile,'for',patch_dict.keys()
746 new=open(newspecfile,"w")
748 for line in spec.readlines():
749 attempt=Module.matcher_rpm_define.match(line)
751 (define,var,value)=attempt.groups()
752 if var in patch_dict.keys():
753 if self.options.debug:
754 print 'rewriting %s as %s'%(var,patch_dict[var])
755 new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
760 for (key,was_changed) in changed.iteritems():
762 if self.options.debug:
763 print 'rewriting missing %s as %s'%(key,patch_dict[key])
764 new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
767 os.rename(newspecfile,specfile)
769 # returns all lines until the magic line
770 def unignored_lines (self, logfile):
772 white_line_matcher = re.compile("\A\s*\Z")
773 for logline in file(logfile).readlines():
774 if logline.strip() == Module.svn_magic_line:
776 elif white_line_matcher.match(logline):
779 result.append(logline.strip()+'\n')
782 # creates a copy of the input with only the unignored lines
783 def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
785 f.write(self.setting_tag_format%new_tag_name + '\n')
786 for line in self.unignored_lines(filein):
790 def insert_changelog (self, logfile, oldtag, newtag):
791 for specfile in self.all_specnames():
792 newspecfile=specfile+".new"
793 if self.options.verbose:
794 print 'Inserting changelog from %s into %s'%(logfile,specfile)
796 new=open(newspecfile,"w")
797 for line in spec.readlines():
799 if re.compile('%changelog').match(line):
800 dateformat="* %a %b %d %Y"
801 datepart=time.strftime(dateformat)
802 logpart="%s <%s> - %s"%(Module.config['username'],
803 Module.config['email'],
805 new.write(datepart+" "+logpart+"\n")
806 for logline in self.unignored_lines(logfile):
807 new.write("- " + logline)
811 os.rename(newspecfile,specfile)
813 def show_dict (self, spec_dict):
814 if self.options.verbose:
815 for (k,v) in spec_dict.iteritems():
818 def last_tag (self, spec_dict):
820 return "%s-%s" % (spec_dict[self.module_version_varname],
821 spec_dict[self.module_taglevel_varname])
823 raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
825 def tag_name (self, spec_dict, old_svn_name=False):
826 base_tag_name = self.name
828 base_tag_name = git_to_svn_name(self.name)
829 return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
832 ##############################
833 # using fine_grain means replacing only those instances that currently refer to this tag
834 # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
835 def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
836 newtagsfile=tagsfile+".new"
838 new=open(newtagsfile,"w")
841 # fine-grain : replace those lines that refer to oldname
843 if self.options.verbose:
844 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
845 matcher=re.compile("^(.*)%s(.*)"%oldname)
846 for line in tags.readlines():
847 if not matcher.match(line):
850 (begin,end)=matcher.match(line).groups()
851 new.write(begin+newname+end+"\n")
853 # brute-force : change uncommented lines that define <module>-SVNPATH
855 if self.options.verbose:
856 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
857 pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
858 %(self.name,self.name)
859 matcher_module=re.compile(pattern)
860 for line in tags.readlines():
861 attempt=matcher_module.match(line)
863 if line.find("-GITPATH") >= 0:
864 modulepath = "%s-GITPATH"%self.name
865 replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
867 modulepath = "%s-SVNPATH"%self.name
868 replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
869 if self.options.verbose:
870 print ' ' + modulepath,
871 new.write(replacement)
877 os.rename(newtagsfile,tagsfile)
878 if self.options.verbose: print "%d changes"%matches
881 def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
882 if self.options.verbose:
883 print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
885 found_tagname = tagname
886 found = self.repository.tag_exists(tagname)
887 if not found and old_svn_tag_name:
888 if self.options.verbose:
890 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
891 found = self.repository.tag_exists(old_svn_tag_name)
893 found_tagname = old_svn_tag_name
895 if (found and need_it) or (not found and not need_it):
896 if self.options.verbose:
898 if found: print "- found"
899 else: print "- not found"
901 if self.options.verbose:
904 raise Exception, "tag (%s) is already there" % tagname
906 raise Exception, "can not find required tag (%s)" % tagname
911 ##############################
913 self.init_module_dir()
914 self.revert_module_dir()
915 self.update_module_dir()
917 spec_dict = self.spec_dict()
918 self.show_dict(spec_dict)
921 old_tag_name = self.tag_name(spec_dict)
922 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
924 if (self.options.new_version):
925 # new version set on command line
926 spec_dict[self.module_version_varname] = self.options.new_version
927 spec_dict[self.module_taglevel_varname] = 0
930 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
931 spec_dict[self.module_taglevel_varname] = new_taglevel
933 new_tag_name = self.tag_name(spec_dict)
936 old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
937 new_tag_name = self.check_tag(new_tag_name, need_it=False)
940 diff_output = self.repository.diff_with_tag(old_tag_name)
941 if len(diff_output) == 0:
942 if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
945 # side effect in trunk's specfile
946 self.patch_spec_var(spec_dict)
948 # prepare changelog file
949 # we use the standard subversion magic string (see svn_magic_line)
950 # so we can provide useful information, such as version numbers and diff
952 changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
953 changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
954 setting_tag_line=Module.setting_tag_format%new_tag_name
955 file(changelog,"w").write("""
958 Please write a changelog for this new tag in the section above
959 """%(Module.svn_magic_line,setting_tag_line))
961 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
962 file(changelog,"a").write('DIFF=========\n' + diff_output)
964 if self.options.debug:
968 self.run("%s %s"%(self.options.editor,changelog))
969 # strip magic line in second file - looks like svn has changed its magic line with 1.6
970 # so we do the job ourselves
971 self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
972 # insert changelog in spec
973 if self.options.changelog:
974 self.insert_changelog (changelog,old_tag_name,new_tag_name)
977 build_path = os.path.join(self.options.workdir,
978 Module.config['build'])
979 build = Repository(build_path, self.options)
980 if self.options.build_branch:
981 build.to_branch(self.options.build_branch)
982 if not build.is_clean():
985 tagsfiles=glob(build.path+"/*-tags*.mk")
986 tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
990 for tagsfile in tagsfiles:
991 status=tagsdict[tagsfile]
992 basename=os.path.basename(tagsfile)
993 print ".................... Dealing with %s"%basename
994 while tagsdict[tagsfile] == 'todo' :
995 choice = prompt ("insert %s in %s "%(new_tag_name,basename),default_answer,
996 [ ('y','es'), ('n', 'ext'), ('f','orce'),
997 ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
1000 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1002 print 'Done with %s'%os.path.basename(tagsfile)
1003 tagsdict[tagsfile]='done'
1005 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1007 print build.diff(f=os.path.basename(tagsfile))
1009 build.revert(f=tagsfile)
1011 self.run("cat %s"%tagsfile)
1014 print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1015 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1016 d: show current diff for this tag file
1017 r: revert that tag file
1018 c: cat the current tag file
1019 n: move to next file"""%locals()
1021 if prompt("Want to review changes on tags files",False):
1022 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1027 def diff_all_changes():
1029 print self.repository.diff()
1031 def commit_all_changes(log):
1032 if hasattr(self,'branch'):
1033 self.repository.commit(log, branch=self.branch)
1035 self.repository.commit(log)
1038 self.run_prompt("Review module and build", diff_all_changes)
1039 self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1040 self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1042 if self.options.debug:
1043 print 'Preserving',changelog,'and stripped',changelog_svn
1045 os.unlink(changelog)
1046 os.unlink(changelog_svn)
1049 ##############################
1050 def do_version (self):
1051 self.init_module_dir()
1052 self.revert_module_dir()
1053 self.update_module_dir()
1054 spec_dict = self.spec_dict()
1055 if self.options.www:
1056 self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1057 self.last_tag(spec_dict)))
1058 for varname in self.varnames:
1059 if not spec_dict.has_key(varname):
1060 self.html_print ('Could not find %%define for %s'%varname)
1063 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1064 self.html_print ("%-16s %s"%('url',self.repository.url()))
1065 if self.options.verbose:
1066 self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1067 self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1068 self.html_print_end()
1071 ##############################
1073 self.init_module_dir()
1074 self.revert_module_dir()
1075 self.update_module_dir()
1076 spec_dict = self.spec_dict()
1077 self.show_dict(spec_dict)
1080 tag_name = self.tag_name(spec_dict)
1081 old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1084 tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1086 if self.options.verbose:
1087 print 'Getting diff'
1088 diff_output = self.repository.diff_with_tag(tag_name)
1090 if self.options.list:
1094 thename=self.friendly_name()
1096 if self.options.www and diff_output:
1097 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1098 thename,self.last_tag(spec_dict),len(diff_output)))
1100 self.html_store_raw ('<p> < (left) %s </p>' % tag_name)
1101 self.html_store_raw ('<p> > (right) %s </p>' % thename)
1102 self.html_store_pre (diff_output)
1103 elif not self.options.www:
1104 print 'x'*30,'module',thename
1105 print 'x'*20,'<',tag_name
1106 print 'x'*20,'>',thename
1109 ##############################
1110 # store and restitute html fragments
1112 def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1115 def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1118 def html_quote (text):
1119 return text.replace('&','&').replace('<','<').replace('>','>')
1121 # only the fake error module has multiple titles
1122 def html_store_title (self, title):
1123 if not hasattr(self,'titles'): self.titles=[]
1124 self.titles.append(title)
1126 def html_store_raw (self, html):
1127 if not hasattr(self,'body'): self.body=''
1130 def html_store_pre (self, text):
1131 if not hasattr(self,'body'): self.body=''
1132 self.body += '<pre>' + self.html_quote(text) + '</pre>'
1134 def html_print (self, txt):
1135 if not self.options.www:
1138 if not hasattr(self,'in_list') or not self.in_list:
1139 self.html_store_raw('<ul>')
1141 self.html_store_raw('<li>'+txt+'</li>')
1143 def html_print_end (self):
1144 if self.options.www:
1145 self.html_store_raw ('</ul>')
1148 def html_dump_header(title):
1149 nowdate=time.strftime("%Y-%m-%d")
1150 nowtime=time.strftime("%H:%M (%Z)")
1151 print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1152 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1155 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1156 <style type="text/css">
1157 body { font-family:georgia, serif; }
1158 h1 {font-size: large; }
1159 p.title {font-size: x-large; }
1160 span.error {text-weight:bold; color: red; }
1164 <p class='title'> %s - status on %s at %s</p>
1166 """%(title,title,nowdate,nowtime)
1169 def html_dump_middle():
1173 def html_dump_footer():
1174 print "</body></html"
1176 def html_dump_toc(self):
1177 if hasattr(self,'titles'):
1178 for title in self.titles:
1179 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1181 def html_dump_body(self):
1182 if hasattr(self,'titles'):
1183 for title in self.titles:
1184 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1185 if hasattr(self,'body'):
1187 print '<p class="top">',self.html_href('#','Back to top'),'</p>'
1191 def release_changelog(options, buildtag1, buildtag2, tagfile):
1192 build = Module("build@%s" % buildtag1, options)
1193 build.init_module_dir()
1195 # tagfile = os.path.join(build.module_dir, tagfile)
1196 # for line in open(tagfile):
1198 # url = line.split(':=')[1]
1199 # print build.parse_module_spec(url)
1203 os.system("cp %s/%s /tmp" % (build.module_dir, tagfile))
1205 build = Module("build@%s" % buildtag2, options)
1206 build.init_module_dir()
1208 print os.system("diff -u /tmp/%s %s/%s" % (tagfile, build.module_dir, tagfile))
1213 ##############################
1216 module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1218 module-tools : a set of tools to manage subversion tags and specfile
1219 requires the specfile to either
1220 * define *version* and *taglevel*
1222 * define redirection variables module_version_varname / module_taglevel_varname
1224 by default, the trunk of modules is taken into account
1225 in this case, just mention the module name as <module_desc>
1227 if you wish to work on a branch rather than on the trunk,
1228 you can use something like e.g. Mom:2.1 as <module_desc>
1230 release_usage="""Usage: %prog [options] tag1 .. tagn
1231 Extract release notes from the changes in specfiles between several build tags, latest first
1233 release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1234 You can refer to a (build) branch by prepending a colon, like in
1235 release-changelog :4.2 4.2-rc25
1236 You can refer to the build trunk by just mentioning 'trunk', e.g.
1237 release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1239 common_usage="""More help:
1240 see http://svn.planet-lab.org/wiki/ModuleTools"""
1243 'list' : "displays a list of available tags or branches",
1244 'version' : "check latest specfile and print out details",
1245 'diff' : "show difference between module (trunk or branch) and latest tag",
1246 'tag' : """increment taglevel in specfile, insert changelog in specfile,
1247 create new tag and and monitor its adoption in build/*-tags*.mk""",
1248 'branch' : """create a branch for this module, from the latest tag on the trunk,
1249 and change trunk's version number to reflect the new branch name;
1250 you can specify the new branch name by using module:branch""",
1251 'sync' : """create a tag from the module
1252 this is a last resort option, mostly for repairs""",
1253 'changelog' : """extract changelog between build tags
1254 expected arguments are a list of tags""",
1257 silent_modes = ['list']
1258 release_modes = ['changelog']
1261 def optparse_list (option, opt, value, parser):
1263 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1265 setattr(parser.values,option.dest,value.split())
1270 for function in Main.modes.keys():
1271 if sys.argv[0].find(function) >= 0:
1275 print "Unsupported command",sys.argv[0]
1276 print "Supported commands:" + " ".join(Main.modes.keys())
1279 if mode not in Main.release_modes:
1280 usage = Main.module_usage
1281 usage += Main.common_usage
1282 usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1284 usage = Main.release_usage
1285 usage += Main.common_usage
1287 parser=OptionParser(usage=usage)
1289 if mode == "tag" or mode == 'branch':
1290 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1291 help="set new version and reset taglevel to 0")
1293 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1294 help="do not update changelog section in specfile when tagging")
1295 parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1296 help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1297 if mode == "tag" or mode == "sync" :
1298 parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1299 help="specify editor")
1301 if mode in ["diff","version"] :
1302 parser.add_option("-W","--www", action="store", dest="www", default=False,
1303 help="export diff in html format, e.g. -W trunk")
1306 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1307 help="just list modules that exhibit differences")
1309 default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1310 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1311 help="run on all modules as found in %s"%default_modules_list)
1312 parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1313 help="run on all modules found in specified file")
1314 parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1315 help="dry run - shell commands are only displayed")
1316 parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1317 default=[], nargs=1,type="string",
1318 help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1319 -- can be set multiple times, or use quotes""")
1321 parser.add_option("-w","--workdir", action="store", dest="workdir",
1322 default="%s/%s"%(os.getenv("HOME"),"modules"),
1323 help="""name for dedicated working dir - defaults to ~/modules
1324 ** THIS MUST NOT ** be your usual working directory""")
1325 parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1326 help="skip safety checks, such as svn updates -- use with care")
1328 # default verbosity depending on function - temp
1329 verbose_modes= ['tag', 'sync', 'branch']
1331 if mode not in verbose_modes:
1332 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
1333 help="run in verbose mode")
1335 parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1336 help="run in quiet (non-verbose) mode")
1337 (options, args) = parser.parse_args()
1339 if not hasattr(options,'dry_run'):
1340 options.dry_run=False
1341 if not hasattr(options,'www'):
1347 if options.all_modules:
1348 options.modules_list=default_modules_list
1349 if options.modules_list:
1350 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1354 Module.init_homedir(options)
1357 if mode not in Main.release_modes:
1358 modules=[ Module(modname,options) for modname in args ]
1359 # hack: create a dummy Module to store errors/warnings
1360 error_module = Module('__errors__',options)
1362 for module in modules:
1363 if len(args)>1 and mode not in Main.silent_modes:
1365 print '========================================',module.friendly_name()
1366 # call the method called do_<mode>
1367 method=Module.__dict__["do_%s"%mode]
1372 title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1373 (module.friendly_name(), str(e))
1374 error_module.html_store_title(title)
1377 traceback.print_exc()
1378 print 'Skipping module %s: '%modname,e
1382 modetitle="Changes to tag in %s"%options.www
1383 elif mode == "version":
1384 modetitle="Latest tags in %s"%options.www
1385 modules.append(error_module)
1386 error_module.html_dump_header(modetitle)
1387 for module in modules:
1388 module.html_dump_toc()
1389 Module.html_dump_middle()
1390 for module in modules:
1391 module.html_dump_body()
1392 Module.html_dump_footer()
1394 release_changelog(options, *args)
1397 ####################
1398 if __name__ == "__main__" :
1401 except KeyboardInterrupt: