3 subversion_id = "$Id: TestMain.py 7635 2008-01-04 09:46:06Z thierry $"
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/%s"%(os.getenv("HOME"),options.modules,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="%s/%s"%(os.getenv("HOME"),options.modules)
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.skip_update:
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 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 for url in [ trunk_url, tag_url ] :
374 if not Svnpath(url,self.options).url_exists():
375 print 'Could not find svn URL %s'%url
378 self.run("svn diff %s %s"%(tag_url,trunk_url))
380 def patch_tags_file (self, tagsfile, oldname, newname):
381 newtagsfile=tagsfile+".new"
382 if self.options.verbose:
383 print 'Replacing %s into %s in %s'%(oldname,newname,tagsfile)
385 new=open(newtagsfile,"w")
386 matcher=re.compile("^(.*)%s(.*)"%oldname)
387 for line in tags.readlines():
388 if not matcher.match(line):
391 (begin,end)=matcher.match(line).groups()
392 new.write(begin+newname+end+"\n")
395 os.rename(newtagsfile,tagsfile)
400 self.revert_trunkdir()
401 self.update_trunkdir()
403 spec_dict = self.spec_dict()
404 self.show_dict(spec_dict)
407 trunk_url=self.trunk_url()
408 old_tag_name = self.tag_name(spec_dict)
409 old_tag_url=self.tag_url(spec_dict)
410 if (self.options.new_version):
411 # new version set on command line
412 spec_dict[self.module_version_varname] = self.options.new_version
413 spec_dict[self.module_taglevel_varname] = 0
416 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
417 spec_dict[self.module_taglevel_varname] = new_taglevel
420 new_tag_name = self.tag_name(spec_dict)
421 new_tag_url=self.tag_url(spec_dict)
422 for url in [ trunk_url, old_tag_url ] :
423 if not Svnpath(url,self.options).url_exists():
424 print 'Could not find svn URL %s'%url
426 if Svnpath(new_tag_url,self.options).url_exists():
427 print 'New tag\'s svn URL %s already exists ! '%url
430 # side effect in trunk's specfile
431 self.patch_spec_var(spec_dict)
433 # prepare changelog file
434 # we use the standard subversion magic string (see svn_magic_line)
435 # so we can provide useful information, such as version numbers and diff
437 changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
438 file(changelog,"w").write("""Tagging module %s -- from %s to %s
441 Please write a changelog for this new tag in the section above
442 """%(self.name,old_tag_name,new_tag_name,Module.svn_magic_line))
444 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
445 self.run("(echo 'DIFF========='; svn diff %s %s) >> %s"%(old_tag_url,trunk_url,changelog))
447 if self.options.debug:
451 self.run("%s %s"%(self.options.editor,changelog))
452 # insert changelog in spec
453 if self.options.changelog:
454 self.insert_changelog (changelog,old_tag_name,new_tag_name)
457 build = Module(self.options.build,self.options)
459 build.init_trunkdir()
460 build.revert_trunkdir()
461 build.update_trunkdir()
463 for tagsfile in glob(build.trunkdir+"/*-tags.mk"):
464 if prompt("Want to adopt new tag in %s"%tagsfile):
465 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name)
468 paths += self.trunkdir + " "
469 paths += build.trunkdir + " "
470 self.run_prompt("Check","svn diff " + paths)
471 self.run_prompt("Commit","svn commit --file %s %s"%(changelog,paths))
472 self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,trunk_url,new_tag_url))
474 if self.options.debug:
475 print 'Preserving',changelog
479 usage="""Usage: %prog options module1 [ .. modulen ]
481 manage subversion tags and specfile
482 requires the specfile to define name, version and taglevel
483 OR alternatively redirection variables like module_version_varname
485 module-diff : show difference between trunk and latest tag
486 module-tag : increment taglevel in specfile, insert changelog in specfile,
487 create new tag and and adopt it in build/*-tags.mk
488 module-init : create initial tag
489 module-version : only check specfile and print out details"""
492 all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
494 parser=OptionParser(usage=usage,version=subversion_id)
495 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
496 help="When tagging, set new version and reset taglevel to 0")
497 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
498 help="Runs all modules as found in %s"%all_modules)
499 parser.add_option("-u","--no-update",action="store_true",dest="skip_update",default=False,
500 help="Skips svn updates")
501 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
502 help="Does not update changelog section in specfile when tagging")
503 parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
504 help="Specify editor")
505 parser.add_option("-m","--message", action="store", dest="message", default=None,
506 help="Specify log message")
507 parser.add_option("-M","--modules", action="store", dest="modules", default="modules",
508 help="Name for topdir - defaults to modules")
509 parser.add_option("-B","--build", action="store", dest="build", default="build",
510 help="Set module name for build, defaults to build")
511 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
512 help="Run in verbose mode")
513 parser.add_option("-d","--debug", action="store_true", dest="debug", default=False,
514 help="Debug mode - mostly more verbose")
515 (options, args) = parser.parse_args()
516 if options.debug: options.verbose=True
519 if options.all_modules:
520 args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
524 Module.init_homedir(options)
526 module=Module(modname,options)
527 if sys.argv[0].find("diff") >= 0:
529 elif sys.argv[0].find("tag") >= 0:
531 elif sys.argv[0].find("init") >= 0:
533 elif sys.argv[0].find("version") >= 0:
536 print "Unsupported command",sys.argv[0]
540 # basically, we exit if anything goes wrong
541 if __name__ == "__main__" :