take util-vserver out of our scope
[build.git] / module-tag.py
1 #!/usr/bin/python -u
2
3 subversion_id = "$Id$"
4
5 import sys, os, os.path
6 import re
7 import time
8 from glob import glob
9 from optparse import OptionParser
10
11 def prompt (question,default=True):
12     if default:
13         question += " [y]/n ? "
14     else:
15         question += " y/[n] ? "
16     try:
17         answer=raw_input(question)
18         if not answer:
19             return default
20         elif answer[0] in [ 'y','Y']:
21             return True
22         elif answer[0] in [ 'n','N']:
23             return False
24         else:
25             return prompt(question,default)
26     except KeyboardInterrupt:
27         print "Aborted"
28         return False
29     except:
30         raise
31
32 class Command:
33     def __init__ (self,command,options):
34         self.command=command
35         self.options=options
36         self.tmp="/tmp/command-%d"%os.getpid()
37
38     def run (self):
39         if self.options.verbose:
40             print '+',self.command
41             sys.stdout.flush()
42         return os.system(self.command)
43
44     def run_silent (self):
45         if self.options.verbose:
46             print '+',self.command,' .. ',
47             sys.stdout.flush()
48         retcod=os.system(self.command + " &> " + self.tmp)
49         if retcod != 0:
50             print "FAILED ! -- output quoted below "
51             os.system("cat " + self.tmp)
52             print "FAILED ! -- end of quoted output"
53         elif self.options.verbose:
54             print "OK"
55         os.unlink(self.tmp)
56         return retcod
57
58     def run_fatal(self):
59         if self.run_silent() !=0:
60             raise Exception,"Command %s failed"%self.command
61
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,' .. ',
67             sys.stdout.flush()
68         command=self.command
69         if with_stderr:
70             command += " &> "
71         else:
72             command += " > "
73         command += tmp
74         os.system(command)
75         result=file(tmp).read()
76         os.unlink(tmp)
77         if self.options.debug:
78             print 'Done',
79         return result
80
81 class Svnpath:
82     def __init__(self,path,options):
83         self.path=path
84         self.options=options
85
86     def url_exists (self):
87         return os.system("svn list %s &> /dev/null"%self.path) == 0
88
89     def dir_needs_revert (self):
90         command="svn status %s"%self.path
91         return len(Command(command,self.options).output_of(True)) != 0
92     # turns out it's the same implem.
93     def file_needs_commit (self):
94         command="svn status %s"%self.path
95         return len(Command(command,self.options).output_of(True)) != 0
96
97 class Module:
98
99     svn_magic_line="--This line, and those below, will be ignored--"
100     
101     redirectors=[ # ('module_name_varname','name'),
102                   ('module_version_varname','version'),
103                   ('module_taglevel_varname','taglevel'), ]
104
105     # where to store user's config
106     config_storage="CONFIG"
107     # 
108     config={}
109
110     import commands
111     configKeys=[ ('svnpath',"Enter your toplevel svnpath",
112                   "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
113                  ("build", "Enter the name of your build module","build"),
114                  ('username',"Enter your firstname and lastname for changelogs",""),
115                  ("email","Enter your email address for changelogs",""),
116                  ]
117
118     @staticmethod
119     def prompt_config ():
120         for (key,message,default) in Module.configKeys:
121             Module.config[key]=""
122             while not Module.config[key]:
123                 Module.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
124
125
126     # for parsing module spec name:branch
127     matcher_branch_spec=re.compile("\A(?P<name>[\w-]+):(?P<branch>[\w\.]+)\Z")
128     matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
129
130     def __init__ (self,module_spec,options):
131         # parse module spec
132         attempt=Module.matcher_branch_spec.match(module_spec)
133         if attempt:
134             self.name=attempt.group('name')
135             self.branch=attempt.group('branch')
136         else:
137             self.name=module_spec
138             self.branch=None
139
140         self.options=options
141         self.moddir="%s/%s"%(options.workdir,self.name)
142
143     def friendly_name (self):
144         if not self.branch:
145             return self.name
146         else:
147             return "%s:%s"%(self.name,self.branch)
148
149     def edge_dir (self):
150         if not self.branch:
151             return "%s/trunk"%(self.moddir)
152         else:
153             return "%s/branches/%s"%(self.moddir,self.branch)
154
155     def tags_dir (self):
156         return "%s/tags"%(self.moddir)
157
158     def run (self,command):
159         return Command(command,self.options).run()
160     def run_fatal (self,command):
161         return Command(command,self.options).run_fatal()
162     def run_prompt (self,message,command):
163         if not self.options.verbose:
164             question=message
165         else:
166             question="Want to run " + command
167         if prompt(question,True):
168             self.run(command)            
169
170     @staticmethod
171     def init_homedir (options):
172         topdir=options.workdir
173         if options.verbose:
174             print 'Checking for',topdir
175         storage="%s/%s"%(topdir,Module.config_storage)
176         # sanity check. Either the topdir exists AND we have a config/storage
177         # or topdir does not exist and we create it
178         # to avoid people use their own daily svn repo
179         if os.path.isdir(topdir) and not os.path.isfile(storage):
180             print """The directory %s exists and has no CONFIG file
181 If this is your regular working directory, please provide another one as the
182 module-* commands need a fresh working dir. Make sure that you do not use 
183 that for other purposes than tagging"""%topdir
184             sys.exit(1)
185         if not os.path.isdir (topdir):
186             print "Cannot find",topdir,"let's create it"
187             Module.prompt_config()
188             print "Checking ...",
189             Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
190             Command("svn co -N %s/%s %s/%s"%(Module.config['svnpath'],
191                                              Module.config['build'],
192                                              topdir,
193                                              Module.config['build']),options).run_fatal()
194             print "OK"
195             
196             # store config
197             f=file(storage,"w")
198             for (key,message,default) in Module.configKeys:
199                 f.write("%s=%s\n"%(key,Module.config[key]))
200             f.close()
201             if options.debug:
202                 print 'Stored',storage
203                 Command("cat %s"%storage,options).run()
204         else:
205             # read config
206             f=open(storage)
207             for line in f.readlines():
208                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
209                 Module.config[key]=value                
210             f.close()
211         if options.verbose:
212             print '******** Using config'
213             for (key,message,default) in Module.configKeys:
214                 print '\t',key,'=',Module.config[key]
215
216     def init_moddir (self):
217         if self.options.verbose:
218             print 'Checking for',self.moddir
219         if not os.path.isdir (self.moddir):
220             self.run_fatal("svn up -N %s"%self.moddir)
221         if not os.path.isdir (self.moddir):
222             print 'Cannot find %s - check module name'%self.moddir
223             sys.exit(1)
224
225     def init_subdir (self,fullpath):
226         if self.options.verbose:
227             print 'Checking for',fullpath
228         if not os.path.isdir (fullpath):
229             self.run_fatal("svn up -N %s"%fullpath)
230
231     def revert_subdir (self,fullpath):
232         if self.options.fast_checks:
233             if self.options.verbose: print 'Skipping revert of %s'%fullpath
234             return
235         if self.options.verbose:
236             print 'Checking whether',fullpath,'needs being reverted'
237         if Svnpath(fullpath,self.options).dir_needs_revert():
238             self.run_fatal("svn revert -R %s"%fullpath)
239
240     def update_subdir (self,fullpath):
241         if self.options.fast_checks:
242             if self.options.verbose: print 'Skipping update of %s'%fullpath
243             return
244         if self.options.verbose:
245             print 'Updating',fullpath
246         self.run_fatal("svn update -N %s"%fullpath)
247
248     def init_edge_dir (self):
249         # if branch, edge_dir is two steps down
250         if self.branch:
251             self.init_subdir("%s/branches"%self.moddir)
252         self.init_subdir(self.edge_dir())
253
254     def revert_edge_dir (self):
255         self.revert_subdir(self.edge_dir())
256
257     def update_edge_dir (self):
258         self.update_subdir(self.edge_dir())
259
260     def main_specname (self):
261         attempt="%s/%s.spec"%(self.edge_dir(),self.name)
262         if os.path.isfile (attempt):
263             return attempt
264         else:
265             try:
266                 return glob("%s/*.spec"%self.edge_dir())[0]
267             except:
268                 print 'Cannot guess specfile for module %s'%self.name
269                 sys.exit(1)
270
271     def all_specnames (self):
272         return glob("%s/*.spec"%self.edge_dir())
273
274     def parse_spec (self, specfile, varnames):
275         if self.options.verbose:
276             print 'Parsing',specfile,
277             for var in varnames:
278                 print "[%s]"%var,
279             print ""
280         result={}
281         f=open(specfile)
282         for line in f.readlines():
283             attempt=Module.matcher_rpm_define.match(line)
284             if attempt:
285                 (define,var,value)=attempt.groups()
286                 if var in varnames:
287                     result[var]=value
288         f.close()
289         if self.options.debug:
290             print 'found',len(result),'keys'
291             for (k,v) in result.iteritems():
292                 print k,'=',v
293         return result
294                 
295     # stores in self.module_name_varname the rpm variable to be used for the module's name
296     # and the list of these names in self.varnames
297     def spec_dict (self):
298         specfile=self.main_specname()
299         redirector_keys = [ varname for (varname,default) in Module.redirectors]
300         redirect_dict = self.parse_spec(specfile,redirector_keys)
301         if self.options.debug:
302             print '1st pass parsing done, redirect_dict=',redirect_dict
303         varnames=[]
304         for (varname,default) in Module.redirectors:
305             if redirect_dict.has_key(varname):
306                 setattr(self,varname,redirect_dict[varname])
307                 varnames += [redirect_dict[varname]]
308             else:
309                 setattr(self,varname,default)
310                 varnames += [ default ] 
311         self.varnames = varnames
312         result = self.parse_spec (specfile,self.varnames)
313         if self.options.debug:
314             print '2st pass parsing done, varnames=',varnames,'result=',result
315         return result
316
317     def patch_spec_var (self, patch_dict):
318         for specfile in self.all_specnames():
319             newspecfile=specfile+".new"
320             if self.options.verbose:
321                 print 'Patching',specfile,'for',patch_dict.keys()
322             spec=open (specfile)
323             new=open(newspecfile,"w")
324
325             for line in spec.readlines():
326                 attempt=Module.matcher_rpm_define.match(line)
327                 if attempt:
328                     (define,var,value)=attempt.groups()
329                     if var in patch_dict.keys():
330                         new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
331                         continue
332                 new.write(line)
333             spec.close()
334             new.close()
335             os.rename(newspecfile,specfile)
336
337     def unignored_lines (self, logfile):
338         result=[]
339         exclude="Tagging module %s"%self.name
340         for logline in file(logfile).readlines():
341             if logline.strip() == Module.svn_magic_line:
342                 break
343             if logline.find(exclude) < 0:
344                 result += [ logline ]
345         return result
346
347     def insert_changelog (self, logfile, oldtag, newtag):
348         for specfile in self.all_specnames():
349             newspecfile=specfile+".new"
350             if self.options.verbose:
351                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
352             spec=open (specfile)
353             new=open(newspecfile,"w")
354             for line in spec.readlines():
355                 new.write(line)
356                 if re.compile('%changelog').match(line):
357                     dateformat="* %a %b %d %Y"
358                     datepart=time.strftime(dateformat)
359                     logpart="%s <%s> - %s %s"%(Module.config['username'],
360                                                  Module.config['email'],
361                                                  oldtag,newtag)
362                     new.write(datepart+" "+logpart+"\n")
363                     for logline in self.unignored_lines(logfile):
364                         new.write("- " + logline)
365                     new.write("\n")
366             spec.close()
367             new.close()
368             os.rename(newspecfile,specfile)
369             
370     def show_dict (self, spec_dict):
371         if self.options.verbose:
372             for (k,v) in spec_dict.iteritems():
373                 print k,'=',v
374
375     def mod_url (self):
376         return "%s/%s"%(Module.config['svnpath'],self.name)
377
378     def edge_url (self):
379         if not self.branch:
380             return "%s/trunk"%(self.mod_url())
381         else:
382             return "%s/branches/%s"%(self.mod_url(),self.branch)
383
384     def tag_name (self, spec_dict):
385         try:
386             return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
387                 self.name,
388                 spec_dict[self.module_version_varname],
389                 spec_dict[self.module_taglevel_varname])
390         except KeyError,err:
391             print 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
392             sys.exit(1)
393
394     def tag_url (self, spec_dict):
395         return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
396
397     def check_svnpath_exists (self, url, message):
398         if self.options.fast_checks:
399             return
400         if self.options.verbose:
401             print 'Checking url (%s) %s'%(url,message),
402         ok=Svnpath(url,self.options).url_exists()
403         if ok:
404             if self.options.verbose: print 'exists - OK'
405         else:
406             if self.options.verbose: print 'KO'
407             print 'Could not find %s URL %s'%(message,url)
408             sys.exit(1)
409     def check_svnpath_not_exists (self, url, message):
410         if self.options.fast_checks:
411             return
412         if self.options.verbose:
413             print 'Checking url (%s) %s'%(url,message),
414         ok=not Svnpath(url,self.options).url_exists()
415         if ok:
416             if self.options.verbose: print 'does not exist - OK'
417         else:
418             if self.options.verbose: print 'KO'
419             print '%s URL %s already exists - exiting'%(message,url)
420             sys.exit(1)
421
422     # locate specfile, parse it, check it and show values
423 ##############################
424     def do_version (self):
425         self.init_moddir()
426         self.init_edge_dir()
427         self.revert_edge_dir()
428         self.update_edge_dir()
429         spec_dict = self.spec_dict()
430         for varname in self.varnames:
431             if not spec_dict.has_key(varname):
432                 print 'Could not find %%define for %s'%varname
433                 return
434             else:
435                 print varname+":",spec_dict[varname]
436         print 'edge url',self.edge_url()
437         print 'latest tag url',self.tag_url(spec_dict)
438         if self.options.verbose:
439             print 'main specfile:',self.main_specname()
440             print 'specfiles:',self.all_specnames()
441
442     init_warning="""WARNING
443 The module-init function has the following limitations
444 * it does not handle changelogs
445 * it does not scan the -tags*.mk files to adopt the new tags"""
446 ##############################
447     def do_init(self):
448         if self.options.verbose:
449             print Module.init_warning
450             if not prompt('Want to proceed anyway'):
451                 return
452
453         self.init_moddir()
454         self.init_edge_dir()
455         self.revert_edge_dir()
456         self.update_edge_dir()
457         spec_dict = self.spec_dict()
458
459         edge_url=self.edge_url()
460         tag_name=self.tag_name(spec_dict)
461         tag_url=self.tag_url(spec_dict)
462         # check the tag does not exist yet
463         self.check_svnpath_not_exists(tag_url,"new tag")
464
465         if self.options.message:
466             svnopt='--message "%s"'%self.options.message
467         else:
468             svnopt='--editor-cmd=%s'%self.options.editor
469         self.run_prompt("Create initial tag",
470                         "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
471
472 ##############################
473     def do_diff (self):
474         self.init_moddir()
475         self.init_edge_dir()
476         self.revert_edge_dir()
477         self.update_edge_dir()
478         spec_dict = self.spec_dict()
479         self.show_dict(spec_dict)
480
481         edge_url=self.edge_url()
482         tag_url=self.tag_url(spec_dict)
483         self.check_svnpath_exists(edge_url,"edge track")
484         self.check_svnpath_exists(tag_url,"latest tag")
485         diff_output = Command("svn diff %s %s"%(tag_url,edge_url),self.options).output_of()
486         if self.options.list:
487             if diff_output:
488                 print self.name
489         else:
490             if not self.options.only or diff_output:
491                 print 'x'*30,'module',self.friendly_name()
492                 print 'x'*20,'<',tag_url
493                 print 'x'*20,'>',edge_url
494                 print diff_output
495
496 ##############################
497     def patch_tags_file (self, tagsfile, oldname, newname):
498         newtagsfile=tagsfile+".new"
499         if self.options.verbose:
500             print 'Replacing %s into %s in %s'%(oldname,newname,tagsfile)
501         tags=open (tagsfile)
502         new=open(newtagsfile,"w")
503         matcher=re.compile("^(.*)%s(.*)"%oldname)
504         for line in tags.readlines():
505             if not matcher.match(line):
506                 new.write(line)
507             else:
508                 (begin,end)=matcher.match(line).groups()
509                 new.write(begin+newname+end+"\n")
510         tags.close()
511         new.close()
512         os.rename(newtagsfile,tagsfile)
513
514     def do_tag (self):
515         self.init_moddir()
516         self.init_edge_dir()
517         self.revert_edge_dir()
518         self.update_edge_dir()
519         # parse specfile
520         spec_dict = self.spec_dict()
521         self.show_dict(spec_dict)
522         
523         # side effects
524         edge_url=self.edge_url()
525         old_tag_name = self.tag_name(spec_dict)
526         old_tag_url=self.tag_url(spec_dict)
527         if (self.options.new_version):
528             # new version set on command line
529             spec_dict[self.module_version_varname] = self.options.new_version
530             spec_dict[self.module_taglevel_varname] = 0
531         else:
532             # increment taglevel
533             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
534             spec_dict[self.module_taglevel_varname] = new_taglevel
535
536         # sanity check
537         new_tag_name = self.tag_name(spec_dict)
538         new_tag_url=self.tag_url(spec_dict)
539         self.check_svnpath_exists (edge_url,"edge track")
540         self.check_svnpath_exists (old_tag_url,"previous tag")
541         self.check_svnpath_not_exists (new_tag_url,"new tag")
542
543         # checking for diffs
544         diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
545                             self.options).output_of()
546         if len(diff_output) == 0:
547             if not prompt ("No difference in trunk for module %s, want to tag anyway"%self.name,False):
548                 return
549
550         # side effect in trunk's specfile
551         self.patch_spec_var(spec_dict)
552
553         # prepare changelog file 
554         # we use the standard subversion magic string (see svn_magic_line)
555         # so we can provide useful information, such as version numbers and diff
556         # in the same file
557         changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
558         file(changelog,"w").write("""Tagging module %s - %s
559
560 %s
561 Please write a changelog for this new tag in the section above
562 """%(self.name,new_tag_name,Module.svn_magic_line))
563
564         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
565             file(changelog,"a").write('DIFF=========\n' + diff_output)
566         
567         if self.options.debug:
568             prompt('Proceed ?')
569
570         # edit it        
571         self.run("%s %s"%(self.options.editor,changelog))
572         # insert changelog in spec
573         if self.options.changelog:
574             self.insert_changelog (changelog,old_tag_name,new_tag_name)
575
576         ## update build
577         try:
578             buildname=Module.config['build']
579         except:
580             buildname="build"
581         build = Module(buildname,self.options)
582         build.init_moddir()
583         build.init_edge_dir()
584         build.revert_edge_dir()
585         build.update_edge_dir()
586         
587         for tagsfile in glob(build.edge_dir()+"/*-tags*.mk"):
588             if prompt("Want to adopt new tag in %s"%tagsfile):
589                 self.patch_tags_file(tagsfile,old_tag_name,new_tag_name)
590
591         paths=""
592         paths += self.edge_dir() + " "
593         paths += build.edge_dir() + " "
594         self.run_prompt("Check","svn diff " + paths)
595         self.run_prompt("Commit","svn commit --file %s %s"%(changelog,paths))
596         self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
597
598         if self.options.debug:
599             print 'Preserving',changelog
600         else:
601             os.unlink(changelog)
602             
603 ##############################
604     def do_branch (self):
605
606         print 'module-branch is experimental - exiting'
607         sys.exit(1)
608
609         if self.branch:
610             print 'Cannot create a branch from another branch - exiting'
611             sys.exit(1)
612         self.init_moddir()
613         
614         # xxx - tmp
615         import readline
616         answer = raw_input ("enter tag name [trunk]").strip()
617         if answer == "" or answer == "trunk":
618             ref="/trunk"
619             from_trunk=True
620         else:
621             ref="/tags/%s-%s"%(self.name,answer)
622             from_trunk=False
623
624         ref_url = "%s/%s"%(self.mod_url(),ref)
625         self.check_svnpath_exists (ref_url,"branch creation point")
626         print "Using starting point %s"%ref_url
627         
628         spec=self.main_specname()
629         if not from_trunk:
630             self.init_subdir(self.tags_dir())
631             workdir="%s/%s"%(self.moddir,ref)
632         else:
633             workdir=self.edge_dir()
634
635         self.init_subdir(workdir)
636         self.revert_subdir(workdir)
637         self.update_subdir(workdir)
638
639         print 'got spec',spec
640         if not os.path.isfile(spec):
641             print 'cannot find spec'
642         
643         # read version & taglevel from the origin specfile
644         print 'parsing',spec
645         origin=self.spec_dict()
646         self.show_dict(origin)
647
648         default_branch=self.options.new_version
649         if not default_branch:
650 #            try:
651                 match=re.compile("\A(?P<main>.*[\.-_])(?P<subid>[0-9]+)\Z").match(origin['version'])
652                 new_subid=int(match.group('subid'))+1
653                 default_branch="%s%d"%(match.group('main'),new_subid)
654 #            except:
655 #                default_branch="not found"
656         new_branch_name=raw_input("Enter branch name [%s] "%default_branch) or default_branch
657         
658         new_branch_url="%s/branches/%s"%(self.mod_url(),new_branch_name)
659         self.check_svnpath_not_exists(new_branch_url,"new branch")
660         print new_branch_name
661         
662
663 ##############################
664 usage="""Usage: %prog options module_desc [ .. module_desc ]
665 Purpose:
666   manage subversion tags and specfile
667   requires the specfile to define *version* and *taglevel*
668   OR alternatively 
669   redirection variables module_version_varname / module_taglevel_varname
670 Trunk:
671   by default, the trunk of modules is taken into account
672   in this case, just mention the module name as <module_desc>
673 Branches:
674   if you wish to work on a branch rather than on the trunk, 
675   you can use the following syntax for <module_desc>
676   Mom:2.1
677       works on Mom/branches/2.1 
678 """
679 # unsupported yet
680 #"""
681 #  branch:Mom
682 #      the branch_id is deduced from the current *version* in the trunk's specfile
683 #      e.g. if Mom/trunk/Mom.spec specifies %define version 2.3, then this script
684 #      would use Mom/branches/2.2
685 #      if if stated %define version 3.0, then the script fails
686 #"""
687
688 functions={ 
689     'diff' : "show difference between trunk and latest tag",
690     'tag'  : """increment taglevel in specfile, insert changelog in specfile,
691                 create new tag and and adopt it in build/*-tags*.mk""",
692     'init' : "create initial tag",
693     'version' : "only check specfile and print out details",
694     'branch' : """create a branch for this module. 
695                 either from trunk, or from a tag""",
696 }
697
698 def main():
699
700     mode=None
701     for function in functions.keys():
702         if sys.argv[0].find(function) >= 0:
703             mode = function
704             break
705     if not mode:
706         print "Unsupported command",sys.argv[0]
707         sys.exit(1)
708
709     global usage
710     usage += "module-%s.py : %s"%(mode,functions[mode])
711     all_modules=os.path.dirname(sys.argv[0])+"/modules.list"
712
713     parser=OptionParser(usage=usage,version=subversion_id)
714     parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
715                       help="run on all modules as found in %s"%all_modules)
716     parser.add_option("-f","--fast-checks",action="store_true",dest="fast_checks",default=False,
717                       help="skip safety checks, such as svn updates -- use with care")
718     if mode == "tag" or mode == 'branch':
719         parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
720                           help="set new version and reset taglevel to 0")
721     if mode == "tag" :
722         parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
723                           help="do not update changelog section in specfile when tagging")
724     if mode == "tag" or mode == "init" :
725         parser.add_option("-e","--editor", action="store", dest="editor", default="emacs",
726                           help="specify editor")
727     if mode == "init" :
728         parser.add_option("-m","--message", action="store", dest="message", default=None,
729                           help="specify log message")
730     if mode == "diff" :
731         parser.add_option("-o","--only", action="store_true", dest="only", default=False,
732                           help="report diff only for modules that exhibit differences")
733     if mode == "diff" :
734         parser.add_option("-l","--list", action="store_true", dest="list", default=False,
735                           help="just list modules that exhibit differences")
736     parser.add_option("-w","--workdir", action="store", dest="workdir", 
737                       default="%s/%s"%(os.getenv("HOME"),"modules"),
738                       help="""name for dedicated working dir - defaults to ~/modules
739 ** THIS MUST NOT ** be your usual working directory""")
740     parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=True, 
741                       help="run in verbose mode")
742     parser.add_option("-q","--quiet", action="store_false", dest="verbose", 
743                       help="run in quiet (non-verbose) mode")
744     parser.add_option("-d","--debug", action="store_true", dest="debug", default=False, 
745                       help="debug mode - mostly more verbose")
746     (options, args) = parser.parse_args()
747
748     if len(args) == 0:
749         if options.all_modules:
750             args=Command("grep -v '#' %s"%all_modules,options).output_of().split()
751         else:
752             parser.print_help()
753             sys.exit(1)
754     Module.init_homedir(options)
755     for modname in args:
756         module=Module(modname,options)
757         print '========================================',module.friendly_name()
758         # call the method called do_<mode>
759         method=Module.__dict__["do_%s"%mode]
760         method(module)
761
762 # basically, we exit if anything goes wrong
763 if __name__ == "__main__" :
764     main()