5 import sys, os, os.path
9 from optparse import OptionParser
11 def prompt (question,default=True):
13 question += " [y]/n ? "
15 question += " y/[n] ? "
17 answer=raw_input(question)
20 elif answer[0] in [ 'y','Y']:
22 elif answer[0] in [ 'n','N']:
25 return prompt(question,default)
26 except KeyboardInterrupt:
33 def __init__ (self,command,options):
36 self.tmp="/tmp/command-%d"%os.getpid()
39 if self.options.verbose:
40 print '+',self.command
42 return os.system(self.command)
44 def run_silent (self):
45 if self.options.verbose:
46 print '+',self.command,' .. ',
48 retcod=os.system(self.command + " &> " + self.tmp)
50 print "FAILED ! -- output quoted below "
51 os.system("cat " + self.tmp)
52 print "FAILED ! -- end of quoted output"
53 elif self.options.verbose:
59 if self.run_silent() !=0:
60 raise Exception,"Command %s failed"%self.command
62 # returns stdout, like bash's $(mycommand)
63 def output_of (self,with_stderr=False):
64 tmp="/tmp/status-%d"%os.getpid()
65 if self.options.debug:
66 print '+',self.command,' .. ',
75 result=file(tmp).read()
77 if self.options.debug:
78 print '+',self.command,'Done',
82 def __init__(self,path,options):
86 def url_exists (self):
87 if self.options.verbose:
88 print 'Checking url',self.path
89 return os.system("svn list %s &> /dev/null"%self.path) == 0
91 def dir_needs_revert (self):
92 command="svn status %s"%self.path
93 return len(Command(command,self.options).output_of(True)) != 0
94 # turns out it's the same implem.
95 def file_needs_commit (self):
96 command="svn status %s"%self.path
97 return len(Command(command,self.options).output_of(True)) != 0
101 # where to store user's config
102 config_storage="CONFIG"
104 configKeys=[ ('svnpath',"Enter your toplevel svnpath (e.g. svn+ssh://thierry@svn.planet-lab.org/svn/)"),
105 ('username',"Enter your firstname and lastname for changelogs"),
106 ("email","Enter your email address for changelogs") ]
109 svn_magic_line="--This line, and those below, will be ignored--"
111 redirectors=[ ('module_name_varname','name'),
112 ('module_version_varname','version'),
113 ('module_taglevel_varname','taglevel'), ]
115 def __init__ (self,name,options):
118 self.moddir="%s/%s"%(options.workdir,name)
119 self.trunkdir="%s/trunk"%(self.moddir)
120 self.varmatcher=re.compile("%define\s+(\S+)\s+(\S*)\s*")
123 def run (self,command):
124 return Command(command,self.options).run()
125 def run_fatal (self,command):
126 return Command(command,self.options).run_fatal()
127 def run_prompt (self,message,command):
128 if not self.options.verbose:
131 question="Want to run " + command
132 if prompt(question,True):
136 def init_homedir (options):
137 topdir=options.workdir
139 print 'Checking for',topdir
140 storage="%s/%s"%(topdir,Module.config_storage)
141 if not os.path.isdir (topdir):
142 # prompt for login or whatever svnpath
143 print "Cannot find",topdir,"let's create it"
144 for (key,message) in Module.configKeys:
145 Module.config[key]=raw_input(message+" : ").strip()
146 Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
149 for (key,message) in Module.configKeys:
150 f.write("%s=%s\n"%(key,Module.config[key]))
153 print 'Stored',storage
154 Command("cat %s"%storage,options).run()
158 for line in f.readlines():
159 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
160 Module.config[key]=value
164 for (key,message) in Module.configKeys:
165 print key,'=',Module.config[key]
167 def init_moddir (self):
168 if self.options.verbose:
169 print 'Checking for',self.moddir
170 if not os.path.isdir (self.moddir):
171 self.run_fatal("svn up -N %s"%self.moddir)
172 if not os.path.isdir (self.moddir):
173 print 'Cannot find %s - check module name'%self.moddir
176 def init_trunkdir (self):
177 if self.options.verbose:
178 print 'Checking for',self.trunkdir
179 if not os.path.isdir (self.trunkdir):
180 self.run_fatal("svn up -N %s"%self.trunkdir)
182 def revert_trunkdir (self):
183 if self.options.verbose:
184 print 'Checking whether',self.trunkdir,'needs being reverted'
185 if Svnpath(self.trunkdir,self.options).dir_needs_revert():
186 self.run_fatal("svn revert -R %s"%self.trunkdir)
188 def update_trunkdir (self):
189 if self.options.fast_checks:
191 if self.options.verbose:
192 print 'Updating',self.trunkdir
193 self.run_fatal("svn update %s"%self.trunkdir)
195 def guess_specname (self):
196 attempt="%s/%s.spec"%(self.trunkdir,self.name)
197 if os.path.isfile (attempt):
201 return glob("%s/*.spec"%self.trunkdir)[0]
203 print 'Cannot guess specfile for module %s'%self.name
206 def parse_spec (self, specfile, varnames):
207 if self.options.debug:
208 print 'parse_spec',specfile,
211 for line in f.readlines():
212 if self.varmatcher.match(line):
213 (var,value)=self.varmatcher.match(line).groups()
217 if self.options.verbose:
218 print 'found',len(result),'keys'
219 if self.options.debug:
220 for (k,v) in result.iteritems():
224 # stores in self.module_name_varname the rpm variable to be used for the module's name
225 # and the list of these names in self.varnames
226 def spec_dict (self):
227 specfile=self.guess_specname()
228 redirector_keys = [ varname for (varname,default) in Module.redirectors]
229 redirect_dict = self.parse_spec(specfile,redirector_keys)
230 if self.options.debug:
231 print '1st pass parsing done, redirect_dict=',redirect_dict
233 for (varname,default) in Module.redirectors:
234 if redirect_dict.has_key(varname):
235 setattr(self,varname,redirect_dict[varname])
236 varnames += [redirect_dict[varname]]
238 setattr(self,varname,default)
239 varnames += [ default ]
240 self.varnames = varnames
241 result = self.parse_spec (specfile,self.varnames)
242 if self.options.debug:
243 print '2st pass parsing done, varnames=',varnames,'result=',result
246 def patch_spec_var (self, patch_dict):
247 specfile=self.guess_specname()
248 newspecfile=specfile+".new"
249 if self.options.verbose:
250 print 'Patching',specfile,'for',patch_dict.keys()
252 new=open(newspecfile,"w")
254 for line in spec.readlines():
255 if self.varmatcher.match(line):
256 (var,value)=self.varmatcher.match(line).groups()
257 if var in patch_dict.keys():
258 new.write('%%define %s %s\n'%(var,patch_dict[var]))
263 os.rename(newspecfile,specfile)
265 def unignored_lines (self, logfile):
267 exclude="Tagging module %s"%self.name
268 for logline in file(logfile).readlines():
269 if logline.strip() == Module.svn_magic_line:
271 if logline.find(exclude) < 0:
272 result += [ logline ]
275 def insert_changelog (self, logfile, oldtag, newtag):
276 specfile=self.guess_specname()
277 newspecfile=specfile+".new"
278 if self.options.verbose:
279 print 'Inserting changelog from %s into %s'%(logfile,specfile)
281 new=open(newspecfile,"w")
282 for line in spec.readlines():
284 if re.compile('%changelog').match(line):
285 dateformat="* %a %b %d %Y"
286 datepart=time.strftime(dateformat)
287 logpart="%s <%s> - %s %s"%(Module.config['username'],
288 Module.config['email'],
290 new.write(datepart+" "+logpart+"\n")
291 for logline in self.unignored_lines(logfile):
292 new.write("- " + logline)
296 os.rename(newspecfile,specfile)
298 def show_dict (self, spec_dict):
299 if self.options.verbose:
300 for (k,v) in spec_dict.iteritems():
303 def trunk_url (self):
304 return "%s/%s/trunk"%(Module.config['svnpath'],self.name)
305 def tag_name (self, spec_dict):
306 return "%s-%s-%s"%(spec_dict[self.module_name_varname],
307 spec_dict[self.module_version_varname],
308 spec_dict[self.module_taglevel_varname])
309 def tag_url (self, spec_dict):
310 return "%s/%s/tags/%s"%(Module.config['svnpath'],self.name,self.tag_name(spec_dict))
312 # locate specfile, parse it, check it and show values
313 def do_version (self):
316 self.revert_trunkdir()
317 self.update_trunkdir()
318 print '==============================',self.name
319 #for (key,message) in Module.configKeys:
320 # print key,':',Module.config[key]
321 spec_dict = self.spec_dict()
322 print 'trunk url',self.trunk_url()
323 print 'latest tag url',self.tag_url(spec_dict)
324 print 'specfile:',self.guess_specname()
325 for varname in self.varnames:
326 if not spec_dict.has_key(varname):
327 print 'Could not find %%define for %s'%varname
330 print varname+":",spec_dict[varname]
332 init_warning="""WARNING
333 The module-init function has the following limitations
334 * it does not handle changelogs
335 * it does not scan the -tags*.mk files to adopt the new tags"""
337 if self.options.verbose:
338 print Module.init_warning
339 if not prompt('Want to proceed anyway'):
344 self.revert_trunkdir()
345 self.update_trunkdir()
346 spec_dict = self.spec_dict()
348 trunk_url=self.trunk_url()
349 tag_name=self.tag_name(spec_dict)
350 tag_url=self.tag_url(spec_dict)
351 # check the tag does not exist yet
352 if not self.options.fast_checks and Svnpath(tag_url,self.options).url_exists():
353 print 'Module %s already has a tag %s'%(self.name,tag_name)
356 if self.options.message:
357 svnopt='--message "%s"'%self.options.message
359 svnopt='--editor-cmd=%s'%self.options.editor
360 self.run_prompt("Create initial tag",
361 "svn copy %s %s %s"%(svnopt,trunk_url,tag_url))
366 self.revert_trunkdir()
367 self.update_trunkdir()
368 spec_dict = self.spec_dict()
369 self.show_dict(spec_dict)
371 trunk_url=self.trunk_url()
372 tag_url=self.tag_url(spec_dict)
373 diff_output = Command("svn diff %s %s"%(tag_url,trunk_url),self.options).output_of()
374 if self.options.list:
378 if not self.options.only or diff_output:
379 print 'x'*40,'module',self.name
380 print 'x'*20,'<',tag_url
381 print 'x'*20,'>',trunk_url
384 def patch_tags_file (self, tagsfile, oldname, newname):
385 newtagsfile=tagsfile+".new"
386 if self.options.verbose:
387 print 'Replacing %s into %s in %s'%(oldname,newname,tagsfile)
389 new=open(newtagsfile,"w")
390 matcher=re.compile("^(.*)%s(.*)"%oldname)
391 for line in tags.readlines():
392 if not matcher.match(line):
395 (begin,end)=matcher.match(line).groups()
396 new.write(begin+newname+end+"\n")
399 os.rename(newtagsfile,tagsfile)
404 self.revert_trunkdir()
405 self.update_trunkdir()
407 spec_dict = self.spec_dict()
408 self.show_dict(spec_dict)
411 trunk_url=self.trunk_url()
412 old_tag_name = self.tag_name(spec_dict)
413 old_tag_url=self.tag_url(spec_dict)
414 if (self.options.new_version):
415 # new version set on command line
416 spec_dict[self.module_version_varname] = self.options.new_version
417 spec_dict[self.module_taglevel_varname] = 0
420 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
421 spec_dict[self.module_taglevel_varname] = new_taglevel
424 new_tag_name = self.tag_name(spec_dict)
425 new_tag_url=self.tag_url(spec_dict)
426 for url in [ trunk_url, old_tag_url ] :
427 if not self.options.fast_checks and not Svnpath(url,self.options).url_exists():
428 print 'Could not find svn URL %s'%url
430 if not self.options.fast_checks and Svnpath(new_tag_url,self.options).url_exists():
431 print 'New tag\'s svn URL %s already exists ! '%url
435 diff_output=Command("svn diff %s %s"%(old_tag_url,trunk_url),
436 self.options).output_of()
437 if len(diff_output) == 0:
438 if not prompt ("No difference in trunk for module %s, want to tag anyway"%self.name,False):
441 # side effect in trunk's specfile
442 self.patch_spec_var(spec_dict)
444 # prepare changelog file
445 # we use the standard subversion magic string (see svn_magic_line)
446 # so we can provide useful information, such as version numbers and diff
448 changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
449 file(changelog,"w").write("""Tagging module %s -- from %s to %s
452 Please write a changelog for this new tag in the section above
453 """%(self.name,old_tag_name,new_tag_name,Module.svn_magic_line))
455 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
456 file(changelog,"a").write('DIFF=========\n' + diff_output)
458 if self.options.debug:
462 self.run("%s %s"%(self.options.editor,changelog))
463 # insert changelog in spec
464 if self.options.changelog:
465 self.insert_changelog (changelog,old_tag_name,new_tag_name)
468 build = Module(self.options.build,self.options)
470 build.init_trunkdir()
471 build.revert_trunkdir()
472 build.update_trunkdir()
474 for tagsfile in glob(build.trunkdir+"/*-tags*.mk"):
475 if prompt("Want to adopt new tag in %s"%tagsfile):
476 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name)
479 paths += self.trunkdir + " "
480 paths += build.trunkdir + " "
481 self.run_prompt("Check","svn diff " + paths)
482 self.run_prompt("Commit","svn commit --file %s %s"%(changelog,paths))
483 self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,trunk_url,new_tag_url))
485 if self.options.debug:
486 print 'Preserving',changelog
490 usage="""Usage: %prog options module1 [ .. modulen ]
492 manage subversion tags and specfile
493 requires the specfile to define name, version and taglevel
494 OR alternatively redirection variables like module_version_varname
497 'diff' : "show difference between trunk and latest tag",
498 'tag' : """increment taglevel in specfile, insert changelog in specfile,
499 create new tag and and adopt it in build/*-tags*.mk""",
500 'init' : "create initial tag",
501 'version' : "only check specfile and print out details"}
505 if sys.argv[0].find("diff") >= 0:
507 elif sys.argv[0].find("tag") >= 0:
509 elif sys.argv[0].find("init") >= 0:
511 elif sys.argv[0].find("version") >= 0:
514 print "Unsupported command",sys.argv[0]
518 usage += "module-%s.py : %s"%(mode,functions[mode])
519 all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
521 parser=OptionParser(usage=usage,version=subversion_id)
522 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
523 help="run on all modules as found in %s"%all_modules)
524 parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
525 help="skip safety checks, such as svn updates -- use with care")
527 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
528 help="set new version and reset taglevel to 0")
530 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
531 help="do not update changelog section in specfile when tagging")
532 if mode == "tag" or mode == "init" :
533 parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
534 help="specify editor")
536 parser.add_option("-m","--message", action="store", dest="message", default=None,
537 help="specify log message")
539 parser.add_option("-o","--only", action="store_true", dest="only", default=False,
540 help="report diff only for modules that exhibit differences")
542 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
543 help="just list modules that exhibit differences")
544 parser.add_option("-w","--workdir", action="store", dest="workdir",
545 default="%s/%s"%(os.getenv("HOME"),"modules"),
546 help="name for workdir - defaults to ~/modules")
547 parser.add_option("-B","--build", action="store", dest="build", default="build",
548 help="set module name for build, defaults to build")
549 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
550 help="run in verbose mode")
551 parser.add_option("-d","--debug", action="store_true", dest="debug", default=False,
552 help="debug mode - mostly more verbose")
553 (options, args) = parser.parse_args()
554 if options.debug: options.verbose=True
557 if options.all_modules:
558 args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
562 Module.init_homedir(options)
564 module=Module(modname,options)
565 if sys.argv[0].find("diff") >= 0:
567 elif sys.argv[0].find("tag") >= 0:
569 elif sys.argv[0].find("init") >= 0:
571 elif sys.argv[0].find("version") >= 0:
574 print "Unsupported command",sys.argv[0]
578 # basically, we exit if anything goes wrong
579 if __name__ == "__main__" :