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"),
107 ("build", "Enter the name of your build module - in general 'build'") ]
110 svn_magic_line="--This line, and those below, will be ignored--"
112 redirectors=[ ('module_name_varname','name'),
113 ('module_version_varname','version'),
114 ('module_taglevel_varname','taglevel'), ]
116 def __init__ (self,name,options):
119 self.moddir="%s/%s"%(options.workdir,name)
120 self.trunkdir="%s/trunk"%(self.moddir)
121 self.varmatcher=re.compile("%define\s+(\S+)\s+(\S*)\s*")
124 def run (self,command):
125 return Command(command,self.options).run()
126 def run_fatal (self,command):
127 return Command(command,self.options).run_fatal()
128 def run_prompt (self,message,command):
129 if not self.options.verbose:
132 question="Want to run " + command
133 if prompt(question,True):
137 def init_homedir (options):
138 topdir=options.workdir
140 print 'Checking for',topdir
141 storage="%s/%s"%(topdir,Module.config_storage)
142 if not os.path.isdir (topdir):
143 # prompt for login or whatever svnpath
144 print "Cannot find",topdir,"let's create it"
145 for (key,message) in Module.configKeys:
146 Module.config[key]=raw_input(message+" : ").strip()
147 Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
150 for (key,message) in Module.configKeys:
151 f.write("%s=%s\n"%(key,Module.config[key]))
154 print 'Stored',storage
155 Command("cat %s"%storage,options).run()
159 for line in f.readlines():
160 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
161 Module.config[key]=value
165 for (key,message) in Module.configKeys:
166 print key,'=',Module.config[key]
168 def init_moddir (self):
169 if self.options.verbose:
170 print 'Checking for',self.moddir
171 if not os.path.isdir (self.moddir):
172 self.run_fatal("svn up -N %s"%self.moddir)
173 if not os.path.isdir (self.moddir):
174 print 'Cannot find %s - check module name'%self.moddir
177 def init_trunkdir (self):
178 if self.options.verbose:
179 print 'Checking for',self.trunkdir
180 if not os.path.isdir (self.trunkdir):
181 self.run_fatal("svn up -N %s"%self.trunkdir)
183 def revert_trunkdir (self):
184 if self.options.verbose:
185 print 'Checking whether',self.trunkdir,'needs being reverted'
186 if Svnpath(self.trunkdir,self.options).dir_needs_revert():
187 self.run_fatal("svn revert -R %s"%self.trunkdir)
189 def update_trunkdir (self):
190 if self.options.fast_checks:
192 if self.options.verbose:
193 print 'Updating',self.trunkdir
194 self.run_fatal("svn update -N %s"%self.trunkdir)
196 def guess_specname (self):
197 attempt="%s/%s.spec"%(self.trunkdir,self.name)
198 if os.path.isfile (attempt):
202 return glob("%s/*.spec"%self.trunkdir)[0]
204 print 'Cannot guess specfile for module %s'%self.name
207 def all_specnames (self):
208 return glob("%s/*.spec"%self.trunkdir)
210 def parse_spec (self, specfile, varnames):
211 if self.options.debug:
212 print 'parse_spec',specfile,
215 for line in f.readlines():
216 if self.varmatcher.match(line):
217 (var,value)=self.varmatcher.match(line).groups()
221 if self.options.verbose:
222 print 'found',len(result),'keys'
223 if self.options.debug:
224 for (k,v) in result.iteritems():
228 # stores in self.module_name_varname the rpm variable to be used for the module's name
229 # and the list of these names in self.varnames
230 def spec_dict (self):
231 specfile=self.guess_specname()
232 redirector_keys = [ varname for (varname,default) in Module.redirectors]
233 redirect_dict = self.parse_spec(specfile,redirector_keys)
234 if self.options.debug:
235 print '1st pass parsing done, redirect_dict=',redirect_dict
237 for (varname,default) in Module.redirectors:
238 if redirect_dict.has_key(varname):
239 setattr(self,varname,redirect_dict[varname])
240 varnames += [redirect_dict[varname]]
242 setattr(self,varname,default)
243 varnames += [ default ]
244 self.varnames = varnames
245 result = self.parse_spec (specfile,self.varnames)
246 if self.options.debug:
247 print '2st pass parsing done, varnames=',varnames,'result=',result
250 def patch_spec_var (self, patch_dict):
251 for specfile in self.all_specnames():
252 newspecfile=specfile+".new"
253 if self.options.verbose:
254 print 'Patching',specfile,'for',patch_dict.keys()
256 new=open(newspecfile,"w")
258 for line in spec.readlines():
259 if self.varmatcher.match(line):
260 (var,value)=self.varmatcher.match(line).groups()
261 if var in patch_dict.keys():
262 new.write('%%define %s %s\n'%(var,patch_dict[var]))
267 os.rename(newspecfile,specfile)
269 def unignored_lines (self, logfile):
271 exclude="Tagging module %s"%self.name
272 for logline in file(logfile).readlines():
273 if logline.strip() == Module.svn_magic_line:
275 if logline.find(exclude) < 0:
276 result += [ logline ]
279 def insert_changelog (self, logfile, oldtag, newtag):
280 for specfile in self.all_specnames():
281 newspecfile=specfile+".new"
282 if self.options.verbose:
283 print 'Inserting changelog from %s into %s'%(logfile,specfile)
285 new=open(newspecfile,"w")
286 for line in spec.readlines():
288 if re.compile('%changelog').match(line):
289 dateformat="* %a %b %d %Y"
290 datepart=time.strftime(dateformat)
291 logpart="%s <%s> - %s %s"%(Module.config['username'],
292 Module.config['email'],
294 new.write(datepart+" "+logpart+"\n")
295 for logline in self.unignored_lines(logfile):
296 new.write("- " + logline)
300 os.rename(newspecfile,specfile)
302 def show_dict (self, spec_dict):
303 if self.options.verbose:
304 for (k,v) in spec_dict.iteritems():
307 def trunk_url (self):
308 return "%s/%s/trunk"%(Module.config['svnpath'],self.name)
309 def tag_name (self, spec_dict):
310 return "%s-%s-%s"%(spec_dict[self.module_name_varname],
311 spec_dict[self.module_version_varname],
312 spec_dict[self.module_taglevel_varname])
313 def tag_url (self, spec_dict):
314 return "%s/%s/tags/%s"%(Module.config['svnpath'],self.name,self.tag_name(spec_dict))
316 # locate specfile, parse it, check it and show values
317 def do_version (self):
320 self.revert_trunkdir()
321 self.update_trunkdir()
322 print '==============================',self.name
323 #for (key,message) in Module.configKeys:
324 # print key,':',Module.config[key]
325 spec_dict = self.spec_dict()
326 print 'trunk url',self.trunk_url()
327 print 'latest tag url',self.tag_url(spec_dict)
328 print 'main specfile:',self.guess_specname()
329 print 'specfiles:',self.all_specnames()
330 for varname in self.varnames:
331 if not spec_dict.has_key(varname):
332 print 'Could not find %%define for %s'%varname
335 print varname+":",spec_dict[varname]
337 init_warning="""WARNING
338 The module-init function has the following limitations
339 * it does not handle changelogs
340 * it does not scan the -tags*.mk files to adopt the new tags"""
342 if self.options.verbose:
343 print Module.init_warning
344 if not prompt('Want to proceed anyway'):
349 self.revert_trunkdir()
350 self.update_trunkdir()
351 spec_dict = self.spec_dict()
353 trunk_url=self.trunk_url()
354 tag_name=self.tag_name(spec_dict)
355 tag_url=self.tag_url(spec_dict)
356 # check the tag does not exist yet
357 if not self.options.fast_checks and Svnpath(tag_url,self.options).url_exists():
358 print 'Module %s already has a tag %s'%(self.name,tag_name)
361 if self.options.message:
362 svnopt='--message "%s"'%self.options.message
364 svnopt='--editor-cmd=%s'%self.options.editor
365 self.run_prompt("Create initial tag",
366 "svn copy %s %s %s"%(svnopt,trunk_url,tag_url))
371 self.revert_trunkdir()
372 self.update_trunkdir()
373 spec_dict = self.spec_dict()
374 self.show_dict(spec_dict)
376 trunk_url=self.trunk_url()
377 tag_url=self.tag_url(spec_dict)
378 diff_output = Command("svn diff %s %s"%(tag_url,trunk_url),self.options).output_of()
379 if self.options.list:
383 if not self.options.only or diff_output:
384 print 'x'*40,'module',self.name
385 print 'x'*20,'<',tag_url
386 print 'x'*20,'>',trunk_url
389 def patch_tags_file (self, tagsfile, oldname, newname):
390 newtagsfile=tagsfile+".new"
391 if self.options.verbose:
392 print 'Replacing %s into %s in %s'%(oldname,newname,tagsfile)
394 new=open(newtagsfile,"w")
395 matcher=re.compile("^(.*)%s(.*)"%oldname)
396 for line in tags.readlines():
397 if not matcher.match(line):
400 (begin,end)=matcher.match(line).groups()
401 new.write(begin+newname+end+"\n")
404 os.rename(newtagsfile,tagsfile)
409 self.revert_trunkdir()
410 self.update_trunkdir()
412 spec_dict = self.spec_dict()
413 self.show_dict(spec_dict)
416 trunk_url=self.trunk_url()
417 old_tag_name = self.tag_name(spec_dict)
418 old_tag_url=self.tag_url(spec_dict)
419 if (self.options.new_version):
420 # new version set on command line
421 spec_dict[self.module_version_varname] = self.options.new_version
422 spec_dict[self.module_taglevel_varname] = 0
425 new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
426 spec_dict[self.module_taglevel_varname] = new_taglevel
429 new_tag_name = self.tag_name(spec_dict)
430 new_tag_url=self.tag_url(spec_dict)
431 for url in [ trunk_url, old_tag_url ] :
432 if not self.options.fast_checks and not Svnpath(url,self.options).url_exists():
433 print 'Could not find svn URL %s'%url
435 if not self.options.fast_checks and Svnpath(new_tag_url,self.options).url_exists():
436 print 'New tag\'s svn URL %s already exists ! '%url
440 diff_output=Command("svn diff %s %s"%(old_tag_url,trunk_url),
441 self.options).output_of()
442 if len(diff_output) == 0:
443 if not prompt ("No difference in trunk for module %s, want to tag anyway"%self.name,False):
446 # side effect in trunk's specfile
447 self.patch_spec_var(spec_dict)
449 # prepare changelog file
450 # we use the standard subversion magic string (see svn_magic_line)
451 # so we can provide useful information, such as version numbers and diff
453 changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
454 file(changelog,"w").write("""Tagging module %s - %s
457 Please write a changelog for this new tag in the section above
458 """%(self.name,new_tag_name,Module.svn_magic_line))
460 if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
461 file(changelog,"a").write('DIFF=========\n' + diff_output)
463 if self.options.debug:
467 self.run("%s %s"%(self.options.editor,changelog))
468 # insert changelog in spec
469 if self.options.changelog:
470 self.insert_changelog (changelog,old_tag_name,new_tag_name)
474 buildname=Module.config['build']
477 build = Module(buildname,self.options)
479 build.init_trunkdir()
480 build.revert_trunkdir()
481 build.update_trunkdir()
483 for tagsfile in glob(build.trunkdir+"/*-tags*.mk"):
484 if prompt("Want to adopt new tag in %s"%tagsfile):
485 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name)
488 paths += self.trunkdir + " "
489 paths += build.trunkdir + " "
490 self.run_prompt("Check","svn diff " + paths)
491 self.run_prompt("Commit","svn commit --file %s %s"%(changelog,paths))
492 self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,trunk_url,new_tag_url))
494 if self.options.debug:
495 print 'Preserving',changelog
499 usage="""Usage: %prog options module1 [ .. modulen ]
501 manage subversion tags and specfile
502 requires the specfile to define name, version and taglevel
503 OR alternatively redirection variables like module_version_varname
506 'diff' : "show difference between trunk and latest tag",
507 'tag' : """increment taglevel in specfile, insert changelog in specfile,
508 create new tag and and adopt it in build/*-tags*.mk""",
509 'init' : "create initial tag",
510 'version' : "only check specfile and print out details"}
514 if sys.argv[0].find("diff") >= 0:
516 elif sys.argv[0].find("tag") >= 0:
518 elif sys.argv[0].find("init") >= 0:
520 elif sys.argv[0].find("version") >= 0:
523 print "Unsupported command",sys.argv[0]
527 usage += "module-%s.py : %s"%(mode,functions[mode])
528 all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
530 parser=OptionParser(usage=usage,version=subversion_id)
531 parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
532 help="run on all modules as found in %s"%all_modules)
533 parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
534 help="skip safety checks, such as svn updates -- use with care")
536 parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
537 help="set new version and reset taglevel to 0")
539 parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
540 help="do not update changelog section in specfile when tagging")
541 if mode == "tag" or mode == "init" :
542 parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
543 help="specify editor")
545 parser.add_option("-m","--message", action="store", dest="message", default=None,
546 help="specify log message")
548 parser.add_option("-o","--only", action="store_true", dest="only", default=False,
549 help="report diff only for modules that exhibit differences")
551 parser.add_option("-l","--list", action="store_true", dest="list", default=False,
552 help="just list modules that exhibit differences")
553 parser.add_option("-w","--workdir", action="store", dest="workdir",
554 default="%s/%s"%(os.getenv("HOME"),"modules"),
555 help="name for workdir - defaults to ~/modules")
556 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
557 help="run in verbose mode")
558 parser.add_option("-d","--debug", action="store_true", dest="debug", default=False,
559 help="debug mode - mostly more verbose")
560 (options, args) = parser.parse_args()
561 if options.debug: options.verbose=True
564 if options.all_modules:
565 args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
569 Module.init_homedir(options)
571 module=Module(modname,options)
572 if sys.argv[0].find("diff") >= 0:
574 elif sys.argv[0].find("tag") >= 0:
576 elif sys.argv[0].find("init") >= 0:
578 elif sys.argv[0].find("version") >= 0:
581 print "Unsupported command",sys.argv[0]
585 # basically, we exit if anything goes wrong
586 if __name__ == "__main__" :