fix
[build.git] / module-tools.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 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase 
12 def prompt (question,default=True,other_choices=[],allow_outside=False):
13     if not isinstance (other_choices,list):
14         other_choices = [ other_choices ]
15     chars = [ c for (c,rest) in other_choices ]
16
17     choices = []
18     if 'y' not in chars:
19         if default is True: choices.append('[y]')
20         else : choices.append('y')
21     if 'n' not in chars:
22         if default is False: choices.append('[n]')
23         else : choices.append('n')
24
25     for (char,choice) in other_choices:
26         if default == char:
27             choices.append("["+char+"]"+choice)
28         else:
29             choices.append("<"+char+">"+choice)
30     try:
31         answer=raw_input(question + " " + "/".join(choices) + " ? ")
32         if not answer:
33             return default
34         answer=answer[0].lower()
35         if answer == 'y':
36             if 'y' in chars: return 'y'
37             else: return True
38         elif answer == 'n':
39             if 'n' in chars: return 'n'
40             else: return False
41         elif other_choices:
42             for (char,choice) in other_choices:
43                 if answer == char:
44                     return char
45             if allow_outside:
46                 return answer
47         return prompt(question,default,other_choices)
48     except:
49         raise
50
51 def default_editor():
52     try:
53         editor = os.environ['EDITOR']
54     except:
55         editor = "emacs"
56     return editor
57
58 ### fold long lines
59 fold_length=132
60
61 def print_fold (line):
62     while len(line) >= fold_length:
63         print line[:fold_length],'\\'
64         line=line[fold_length:]
65     print line
66
67 class Command:
68     def __init__ (self,command,options):
69         self.command=command
70         self.options=options
71         self.tmp="/tmp/command-%d"%os.getpid()
72
73     def run (self):
74         if self.options.dry_run:
75             print 'dry_run',self.command
76             return 0
77         if self.options.verbose and self.options.mode not in Main.silent_modes:
78             print '+',self.command
79             sys.stdout.flush()
80         return os.system(self.command)
81
82     def run_silent (self):
83         if self.options.dry_run:
84             print 'dry_run',self.command
85             return 0
86         if self.options.verbose:
87             print '+',self.command,' .. ',
88             sys.stdout.flush()
89         retcod=os.system(self.command + " &> " + self.tmp)
90         if retcod != 0:
91             print "FAILED ! -- out+err below (command was %s)"%self.command
92             os.system("cat " + self.tmp)
93             print "FAILED ! -- end of quoted output"
94         elif self.options.verbose:
95             print "OK"
96         os.unlink(self.tmp)
97         return retcod
98
99     def run_fatal(self):
100         if self.run_silent() !=0:
101             raise Exception,"Command %s failed"%self.command
102
103     # returns stdout, like bash's $(mycommand)
104     def output_of (self,with_stderr=False):
105         if self.options.dry_run:
106             print 'dry_run',self.command
107             return 'dry_run output'
108         tmp="/tmp/status-%d"%os.getpid()
109         if self.options.debug:
110             print '+',self.command,' .. ',
111             sys.stdout.flush()
112         command=self.command
113         if with_stderr:
114             command += " &> "
115         else:
116             command += " > "
117         command += tmp
118         os.system(command)
119         result=file(tmp).read()
120         os.unlink(tmp)
121         if self.options.debug:
122             print 'Done',
123         return result
124
125 class Svnpath:
126     def __init__(self,path,options):
127         self.path=path
128         self.options=options
129
130     def url_exists (self):
131         return os.system("svn list %s &> /dev/null"%self.path) == 0
132
133     def dir_needs_revert (self):
134         command="svn status %s"%self.path
135         return len(Command(command,self.options).output_of(True)) != 0
136     # turns out it's the same implem.
137     def file_needs_commit (self):
138         command="svn status %s"%self.path
139         return len(Command(command,self.options).output_of(True)) != 0
140
141 # support for tagged module is minimal, and is for the Build class only
142 class Module:
143
144     svn_magic_line="--This line, and those below, will be ignored--"
145     
146     redirectors=[ # ('module_name_varname','name'),
147                   ('module_version_varname','version'),
148                   ('module_taglevel_varname','taglevel'), ]
149
150     # where to store user's config
151     config_storage="CONFIG"
152     # 
153     config={}
154
155     import commands
156     configKeys=[ ('svnpath',"Enter your toplevel svnpath",
157                   "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
158                  ("build", "Enter the name of your build module","build"),
159                  ('username',"Enter your firstname and lastname for changelogs",""),
160                  ("email","Enter your email address for changelogs",""),
161                  ]
162
163     @staticmethod
164     def prompt_config ():
165         for (key,message,default) in Module.configKeys:
166             Module.config[key]=""
167             while not Module.config[key]:
168                 Module.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
169
170
171     # for parsing module spec name:branch
172     matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
173     # special form for tagged module - for Build
174     matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
175     # parsing specfiles
176     matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
177
178     def __init__ (self,module_spec,options):
179         # parse module spec
180         attempt=Module.matcher_branch_spec.match(module_spec)
181         if attempt:
182             self.name=attempt.group('name')
183             self.branch=attempt.group('branch')
184         else:
185             attempt=Module.matcher_tag_spec.match(module_spec)
186             if attempt:
187                 self.name=attempt.group('name')
188                 self.tagname=attempt.group('tagname')
189             else:
190                 self.name=module_spec
191
192         self.options=options
193         self.module_dir="%s/%s"%(options.workdir,self.name)
194
195     def friendly_name (self):
196         if hasattr(self,'branch'):
197             return "%s:%s"%(self.name,self.branch)
198         elif hasattr(self,'tagname'):
199             return "%s@%s"%(self.name,self.tagname)
200         else:
201             return self.name
202
203     def edge_dir (self):
204         if hasattr(self,'branch'):
205             return "%s/branches/%s"%(self.module_dir,self.branch)
206         elif hasattr(self,'tagname'):
207             return "%s/tags/%s"%(self.module_dir,self.tagname)
208         else:
209             return "%s/trunk"%(self.module_dir)
210
211     def tags_dir (self):
212         return "%s/tags"%(self.module_dir)
213
214     def run (self,command):
215         return Command(command,self.options).run()
216     def run_fatal (self,command):
217         return Command(command,self.options).run_fatal()
218     def run_prompt (self,message,command):
219         if not self.options.verbose:
220             while True:
221                 choice=prompt(message,True,('s','how'))
222                 if choice is True:
223                     self.run(command)
224                     return
225                 elif choice is False:
226                     return
227                 else:
228                     print 'About to run:',command
229         else:
230             question=message+" - want to run " + command
231             if prompt(question,True):
232                 self.run(command)            
233
234     ####################
235     # store and restitute html fragments
236     @staticmethod 
237     def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
238     @staticmethod 
239     def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
240
241     # only the fake error module has multiple titles
242     def html_store_title (self, title):
243         if not hasattr(self,'titles'): self.titles=[]
244         self.titles.append(title)
245     def html_store_raw (self, html):
246         if not hasattr(self,'body'): self.body=''
247         self.body += html
248     def html_store_pre (self, text):
249         if not hasattr(self,'body'): self.body=''
250         self.body += '<pre>' + text + '</pre>'
251
252     def html_dump_header(self):
253         now=time.strftime("%Y-%m-%d %H:%M")
254         print """
255 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
256 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
257 <head>
258 <title> Pending changes in %s </title>
259 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
260 <style type="text/css">
261 body { font-family:georgia, serif; }
262 h1 {font-size: large; }
263 p.title {font-size: x-large; }
264 span.error {text-weight:bold; color: red; }
265 </style>
266 </head>
267 <body>
268 <p class='title'> Pending changes in %s - status at %s</p>
269 <ul>
270 """%(self.options.www,self.options.www,now)
271
272     @staticmethod
273     def html_dump_middle():
274         print "</ul>"
275
276     @staticmethod
277     def html_dump_footer():
278         print "</body></html"
279
280     def html_dump_toc(self):
281         if hasattr(self,'titles'):
282             for title in self.titles:
283                 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
284
285     def html_dump_body(self):
286         if hasattr(self,'titles'):
287             for title in self.titles:
288                 print ('<hr />')
289                 print '<h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
290         if hasattr(self,'body'):
291             print self.body
292
293     ####################
294     @staticmethod
295     def init_homedir (options):
296         topdir=options.workdir
297         if options.verbose and options.mode not in Main.silent_modes:
298             print 'Checking for',topdir
299         storage="%s/%s"%(topdir,Module.config_storage)
300         # sanity check. Either the topdir exists AND we have a config/storage
301         # or topdir does not exist and we create it
302         # to avoid people use their own daily svn repo
303         if os.path.isdir(topdir) and not os.path.isfile(storage):
304             print """The directory %s exists and has no CONFIG file
305 If this is your regular working directory, please provide another one as the
306 module-* commands need a fresh working dir. Make sure that you do not use 
307 that for other purposes than tagging"""%topdir
308             sys.exit(1)
309         if not os.path.isdir (topdir):
310             print "Cannot find",topdir,"let's create it"
311             Module.prompt_config()
312             print "Checking ...",
313             Command("svn co -N %s %s"%(Module.config['svnpath'],topdir),options).run_fatal()
314             Command("svn co -N %s/%s %s/%s"%(Module.config['svnpath'],
315                                              Module.config['build'],
316                                              topdir,
317                                              Module.config['build']),options).run_fatal()
318             print "OK"
319             
320             # store config
321             f=file(storage,"w")
322             for (key,message,default) in Module.configKeys:
323                 f.write("%s=%s\n"%(key,Module.config[key]))
324             f.close()
325             if options.debug:
326                 print 'Stored',storage
327                 Command("cat %s"%storage,options).run()
328         else:
329             # read config
330             f=open(storage)
331             for line in f.readlines():
332                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
333                 Module.config[key]=value                
334             f.close()
335         if options.verbose and options.mode not in Main.silent_modes:
336             print '******** Using config'
337             for (key,message,default) in Module.configKeys:
338                 print '\t',key,'=',Module.config[key]
339
340     def init_module_dir (self):
341         if self.options.verbose:
342             print 'Checking for',self.module_dir
343         if not os.path.isdir (self.module_dir):
344             self.run_fatal("svn update -N %s"%self.module_dir)
345         if not os.path.isdir (self.module_dir):
346             raise Exception, 'Cannot find %s - check module name'%self.module_dir
347
348     def init_subdir (self,fullpath):
349         if self.options.verbose:
350             print 'Checking for',fullpath
351         if not os.path.isdir (fullpath):
352             self.run_fatal("svn update -N %s"%fullpath)
353
354     def revert_subdir (self,fullpath):
355         if self.options.fast_checks:
356             if self.options.verbose: print 'Skipping revert of %s'%fullpath
357             return
358         if self.options.verbose:
359             print 'Checking whether',fullpath,'needs being reverted'
360         if Svnpath(fullpath,self.options).dir_needs_revert():
361             self.run_fatal("svn revert -R %s"%fullpath)
362
363     def update_subdir (self,fullpath):
364         if self.options.fast_checks:
365             if self.options.verbose: print 'Skipping update of %s'%fullpath
366             return
367         if self.options.verbose:
368             print 'Updating',fullpath
369         self.run_fatal("svn update -N %s"%fullpath)
370
371     def init_edge_dir (self):
372         # if branch, edge_dir is two steps down
373         if hasattr(self,'branch'):
374             self.init_subdir("%s/branches"%self.module_dir)
375         elif hasattr(self,'tagname'):
376             self.init_subdir("%s/tags"%self.module_dir)
377         self.init_subdir(self.edge_dir())
378
379     def revert_edge_dir (self):
380         self.revert_subdir(self.edge_dir())
381
382     def update_edge_dir (self):
383         self.update_subdir(self.edge_dir())
384
385     def main_specname (self):
386         attempt="%s/%s.spec"%(self.edge_dir(),self.name)
387         if os.path.isfile (attempt):
388             return attempt
389         else:
390             pattern="%s/*.spec"%self.edge_dir()
391             try:
392                 return glob(pattern)[0]
393             except:
394                 raise Exception, 'Cannot guess specfile for module %s -- pattern was %s'%(self.name,pattern)
395
396     def all_specnames (self):
397         return glob("%s/*.spec"%self.edge_dir())
398
399     def parse_spec (self, specfile, varnames):
400         if self.options.verbose:
401             print 'Parsing',specfile,
402             for var in varnames:
403                 print "[%s]"%var,
404             print ""
405         result={}
406         f=open(specfile)
407         for line in f.readlines():
408             attempt=Module.matcher_rpm_define.match(line)
409             if attempt:
410                 (define,var,value)=attempt.groups()
411                 if var in varnames:
412                     result[var]=value
413         f.close()
414         if self.options.debug:
415             print 'found',len(result),'keys'
416             for (k,v) in result.iteritems():
417                 print k,'=',v
418         return result
419                 
420     # stores in self.module_name_varname the rpm variable to be used for the module's name
421     # and the list of these names in self.varnames
422     def spec_dict (self):
423         specfile=self.main_specname()
424         redirector_keys = [ varname for (varname,default) in Module.redirectors]
425         redirect_dict = self.parse_spec(specfile,redirector_keys)
426         if self.options.debug:
427             print '1st pass parsing done, redirect_dict=',redirect_dict
428         varnames=[]
429         for (varname,default) in Module.redirectors:
430             if redirect_dict.has_key(varname):
431                 setattr(self,varname,redirect_dict[varname])
432                 varnames += [redirect_dict[varname]]
433             else:
434                 setattr(self,varname,default)
435                 varnames += [ default ] 
436         self.varnames = varnames
437         result = self.parse_spec (specfile,self.varnames)
438         if self.options.debug:
439             print '2st pass parsing done, varnames=',varnames,'result=',result
440         return result
441
442     def patch_spec_var (self, patch_dict,define_missing=False):
443         for specfile in self.all_specnames():
444             # record the keys that were changed
445             changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
446             newspecfile=specfile+".new"
447             if self.options.verbose:
448                 print 'Patching',specfile,'for',patch_dict.keys()
449             spec=open (specfile)
450             new=open(newspecfile,"w")
451
452             for line in spec.readlines():
453                 attempt=Module.matcher_rpm_define.match(line)
454                 if attempt:
455                     (define,var,value)=attempt.groups()
456                     if var in patch_dict.keys():
457                         if self.options.debug:
458                             print 'rewriting %s as %s'%(var,patch_dict[var])
459                         new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
460                         changed[var]=True
461                         continue
462                 new.write(line)
463             if define_missing:
464                 for (key,was_changed) in changed.iteritems():
465                     if not was_changed:
466                         if self.options.debug:
467                             print 'rewriting missing %s as %s'%(key,patch_dict[key])
468                         new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
469             spec.close()
470             new.close()
471             os.rename(newspecfile,specfile)
472
473     def unignored_lines (self, logfile):
474         result=[]
475         exclude="Setting tag %s"%self.name
476         white_line_matcher = re.compile("\A\s*\Z")
477         for logline in file(logfile).readlines():
478             if logline.strip() == Module.svn_magic_line:
479                 break
480             if logline.find(exclude) >= 0:
481                 continue
482             elif white_line_matcher.match(logline):
483                 continue
484             else:
485                 result.append(logline.strip()+'\n')
486         return result
487
488     def insert_changelog (self, logfile, oldtag, newtag):
489         for specfile in self.all_specnames():
490             newspecfile=specfile+".new"
491             if self.options.verbose:
492                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
493             spec=open (specfile)
494             new=open(newspecfile,"w")
495             for line in spec.readlines():
496                 new.write(line)
497                 if re.compile('%changelog').match(line):
498                     dateformat="* %a %b %d %Y"
499                     datepart=time.strftime(dateformat)
500                     logpart="%s <%s> - %s"%(Module.config['username'],
501                                                  Module.config['email'],
502                                                  newtag)
503                     new.write(datepart+" "+logpart+"\n")
504                     for logline in self.unignored_lines(logfile):
505                         new.write("- " + logline)
506                     new.write("\n")
507             spec.close()
508             new.close()
509             os.rename(newspecfile,specfile)
510             
511     def show_dict (self, spec_dict):
512         if self.options.verbose:
513             for (k,v) in spec_dict.iteritems():
514                 print k,'=',v
515
516     def mod_url (self):
517         return "%s/%s"%(Module.config['svnpath'],self.name)
518
519     def edge_url (self):
520         if hasattr(self,'branch'):
521             return "%s/branches/%s"%(self.mod_url(),self.branch)
522         elif hasattr(self,'tagname'):
523             return "%s/tags/%s"%(self.mod_url(),self.tagname)
524         else:
525             return "%s/trunk"%(self.mod_url())
526
527     def tag_name (self, spec_dict):
528         try:
529             return "%s-%s-%s"%(#spec_dict[self.module_name_varname],
530                 self.name,
531                 spec_dict[self.module_version_varname],
532                 spec_dict[self.module_taglevel_varname])
533         except KeyError,err:
534             raise Exception, 'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
535
536     def tag_url (self, spec_dict):
537         return "%s/tags/%s"%(self.mod_url(),self.tag_name(spec_dict))
538
539     def check_svnpath_exists (self, url, message):
540         if self.options.fast_checks:
541             return
542         if self.options.verbose:
543             print 'Checking url (%s) %s'%(url,message),
544         ok=Svnpath(url,self.options).url_exists()
545         if ok:
546             if self.options.verbose: print 'exists - OK'
547         else:
548             if self.options.verbose: print 'KO'
549             raise Exception, 'Could not find %s URL %s'%(message,url)
550
551     def check_svnpath_not_exists (self, url, message):
552         if self.options.fast_checks:
553             return
554         if self.options.verbose:
555             print 'Checking url (%s) %s'%(url,message),
556         ok=not Svnpath(url,self.options).url_exists()
557         if ok:
558             if self.options.verbose: print 'does not exist - OK'
559         else:
560             if self.options.verbose: print 'KO'
561             raise Exception, '%s URL %s already exists - exiting'%(message,url)
562
563     # locate specfile, parse it, check it and show values
564
565 ##############################
566     def do_version (self):
567         self.init_module_dir()
568         self.init_edge_dir()
569         self.revert_edge_dir()
570         self.update_edge_dir()
571         spec_dict = self.spec_dict()
572         for varname in self.varnames:
573             if not spec_dict.has_key(varname):
574                 print 'Could not find %%define for %s'%varname
575                 return
576             else:
577                 print "%-16s %s"%(varname,spec_dict[varname])
578         if self.options.show_urls:
579             print "%-16s %s"%('edge url',self.edge_url())
580             print "%-16s %s"%('latest tag url',self.tag_url(spec_dict))
581         if self.options.verbose:
582             print "%-16s %s"%('main specfile:',self.main_specname())
583             print "%-16s %s"%('specfiles:',self.all_specnames())
584
585 ##############################
586     def do_list (self):
587 #        print 'verbose',self.options.verbose
588 #        print 'list_tags',self.options.list_tags
589 #        print 'list_branches',self.options.list_branches
590 #        print 'all_modules',self.options.all_modules
591         
592         (verbose,branches,pattern,exact) = (self.options.verbose,self.options.list_branches,
593                                             self.options.list_pattern,self.options.list_exact)
594
595         extra_command=""
596         extra_message=""
597         if hasattr(self,'branch'):
598             pattern=self.branch
599         if pattern or exact:
600             if exact:
601                 if verbose: grep="%s/$"%exact
602                 else: grep="^%s$"%exact
603             else:
604                 grep=pattern
605             extra_command=" | grep %s"%grep
606             extra_message=" matching %s"%grep
607
608         if not branches:
609             message="==================== tags for %s"%self.friendly_name()
610             command="svn list "
611             if verbose: command+="--verbose "
612             command += "%s/tags"%self.mod_url()
613             command += extra_command
614             message += extra_message
615             if verbose: print message
616             self.run(command)
617
618         else:
619             message="==================== branches for %s"%self.friendly_name()
620             command="svn list "
621             if verbose: command+="--verbose "
622             command += "%s/branches"%self.mod_url()
623             command += extra_command
624             message += extra_message
625             if verbose: print message
626             self.run(command)
627
628 ##############################
629     sync_warning="""*** WARNING
630 The module-sync function has the following limitations
631 * it does not handle changelogs
632 * it does not scan the -tags*.mk files to adopt the new tags"""
633
634     def do_sync(self):
635         if self.options.verbose:
636             print Module.sync_warning
637             if not prompt('Want to proceed anyway'):
638                 return
639
640         self.init_module_dir()
641         self.init_edge_dir()
642         self.revert_edge_dir()
643         self.update_edge_dir()
644         spec_dict = self.spec_dict()
645
646         edge_url=self.edge_url()
647         tag_name=self.tag_name(spec_dict)
648         tag_url=self.tag_url(spec_dict)
649         # check the tag does not exist yet
650         self.check_svnpath_not_exists(tag_url,"new tag")
651
652         if self.options.message:
653             svnopt='--message "%s"'%self.options.message
654         else:
655             svnopt='--editor-cmd=%s'%self.options.editor
656         self.run_prompt("Create initial tag",
657                         "svn copy %s %s %s"%(svnopt,edge_url,tag_url))
658
659 ##############################
660     def do_diff (self,compute_only=False):
661         self.init_module_dir()
662         self.init_edge_dir()
663         self.revert_edge_dir()
664         self.update_edge_dir()
665         spec_dict = self.spec_dict()
666         self.show_dict(spec_dict)
667
668         edge_url=self.edge_url()
669         tag_url=self.tag_url(spec_dict)
670         self.check_svnpath_exists(edge_url,"edge track")
671         self.check_svnpath_exists(tag_url,"latest tag")
672         command="svn diff %s %s"%(tag_url,edge_url)
673         if compute_only:
674             if self.options.verbose:
675                 print 'Getting diff with %s'%command
676         diff_output = Command(command,self.options).output_of()
677         # if used as a utility
678         if compute_only:
679             return (spec_dict,edge_url,tag_url,diff_output)
680         # otherwise print the result
681         if self.options.list:
682             if diff_output:
683                 print self.name
684         else:
685             anchor=self.friendly_name()
686             do_print=False
687             if self.options.www and diff_output:
688                 self.html_store_title("Diffs in module %s (%d chars)"%(anchor,len(diff_output)))
689                 link=self.html_href(tag_url,tag_url)
690                 self.html_store_raw ('<p> &lt; (left) %s </p>'%link)
691                 link=self.html_href(edge_url,edge_url)
692                 self.html_store_raw ('<p> &gt; (right) %s </p>'%link)
693                 self.html_store_pre (diff_output)
694             elif not self.options.www:
695                 print 'x'*30,'module',anchor
696                 print 'x'*20,'<',tag_url
697                 print 'x'*20,'>',edge_url
698                 print diff_output
699
700 ##############################
701     # using fine_grain means replacing only those instances that currently refer to this tag
702     # otherwise, <module>-SVNPATH is replaced unconditionnally
703     def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
704         newtagsfile=tagsfile+".new"
705         tags=open (tagsfile)
706         new=open(newtagsfile,"w")
707
708         matches=0
709         # fine-grain : replace those lines that refer to oldname
710         if fine_grain:
711             if self.options.verbose:
712                 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
713             matcher=re.compile("^(.*)%s(.*)"%oldname)
714             for line in tags.readlines():
715                 if not matcher.match(line):
716                     new.write(line)
717                 else:
718                     (begin,end)=matcher.match(line).groups()
719                     new.write(begin+newname+end+"\n")
720                     matches += 1
721         # brute-force : change uncommented lines that define <module>-SVNPATH
722         else:
723             if self.options.verbose:
724                 print 'Searching for -SVNPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
725             pattern="\A\s*(?P<make_name>[^\s]+)-SVNPATH\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s/[^\s]+"\
726                                           %(self.name)
727             matcher_module=re.compile(pattern)
728             for line in tags.readlines():
729                 attempt=matcher_module.match(line)
730                 if attempt:
731                     svnpath="%s-SVNPATH"%(attempt.group('make_name'))
732                     if self.options.verbose:
733                         print ' '+svnpath, 
734                     replacement = "%-32s:= %s/%s/tags/%s\n"%(svnpath,attempt.group('url_main'),self.name,newname)
735                     new.write(replacement)
736                     matches += 1
737                 else:
738                     new.write(line)
739         tags.close()
740         new.close()
741         os.rename(newtagsfile,tagsfile)
742         if self.options.verbose: print "%d changes"%matches
743         return matches
744
745     def do_tag (self):
746         self.init_module_dir()
747         self.init_edge_dir()
748         self.revert_edge_dir()
749         self.update_edge_dir()
750         # parse specfile
751         spec_dict = self.spec_dict()
752         self.show_dict(spec_dict)
753         
754         # side effects
755         edge_url=self.edge_url()
756         old_tag_name = self.tag_name(spec_dict)
757         old_tag_url=self.tag_url(spec_dict)
758         if (self.options.new_version):
759             # new version set on command line
760             spec_dict[self.module_version_varname] = self.options.new_version
761             spec_dict[self.module_taglevel_varname] = 0
762         else:
763             # increment taglevel
764             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
765             spec_dict[self.module_taglevel_varname] = new_taglevel
766
767         # sanity check
768         new_tag_name = self.tag_name(spec_dict)
769         new_tag_url=self.tag_url(spec_dict)
770         self.check_svnpath_exists (edge_url,"edge track")
771         self.check_svnpath_exists (old_tag_url,"previous tag")
772         self.check_svnpath_not_exists (new_tag_url,"new tag")
773
774         # checking for diffs
775         diff_output=Command("svn diff %s %s"%(old_tag_url,edge_url),
776                             self.options).output_of()
777         if len(diff_output) == 0:
778             if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
779                 return
780
781         # side effect in trunk's specfile
782         self.patch_spec_var(spec_dict)
783
784         # prepare changelog file 
785         # we use the standard subversion magic string (see svn_magic_line)
786         # so we can provide useful information, such as version numbers and diff
787         # in the same file
788         changelog="/tmp/%s-%d.txt"%(self.name,os.getpid())
789         file(changelog,"w").write("""Setting tag %s
790
791 %s
792 Please write a changelog for this new tag in the section above
793 """%(new_tag_name,Module.svn_magic_line))
794
795         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
796             file(changelog,"a").write('DIFF=========\n' + diff_output)
797         
798         if self.options.debug:
799             prompt('Proceed ?')
800
801         # edit it        
802         self.run("%s %s"%(self.options.editor,changelog))
803         # insert changelog in spec
804         if self.options.changelog:
805             self.insert_changelog (changelog,old_tag_name,new_tag_name)
806
807         ## update build
808         try:
809             buildname=Module.config['build']
810         except:
811             buildname="build"
812         if self.options.build_branch:
813             buildname+=":"+self.options.build_branch
814         build = Module(buildname,self.options)
815         build.init_module_dir()
816         build.init_edge_dir()
817         build.revert_edge_dir()
818         build.update_edge_dir()
819         
820         tagsfiles=glob(build.edge_dir()+"/*-tags*.mk")
821         tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
822         default_answer = 'y'
823         while True:
824             for (tagsfile,status) in tagsdict.iteritems():
825                 basename=os.path.basename(tagsfile)
826                 print ".................... Dealing with %s"%basename
827                 while tagsdict[tagsfile] == 'todo' :
828                     choice = prompt ("insert %s in %s    "%(new_tag_name,basename),default_answer,
829                                      [ ('y','es'), ('n', 'ext'), ('f','orce'), 
830                                        ('d','iff'), ('r','evert'), ('h','elp') ] ,
831                                      allow_outside=True)
832                     if choice == 'y':
833                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
834                     elif choice == 'n':
835                         print 'Done with %s'%os.path.basename(tagsfile)
836                         tagsdict[tagsfile]='done'
837                     elif choice == 'f':
838                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
839                     elif choice == 'd':
840                         self.run("svn diff %s"%tagsfile)
841                     elif choice == 'r':
842                         self.run("svn revert %s"%tagsfile)
843                     else:
844                         name=self.name
845                         print """y: change %(name)s-SVNPATH only if it currently refers to %(old_tag_name)s
846 f: unconditionnally change any line setting %(name)s-SVNPATH to using %(new_tag_name)s
847 d: show current diff for this tag file
848 r: revert that tag file
849 n: move to next file"""%locals()
850
851             if prompt("Want to review changes on tags files",False):
852                 tagsdict = dict ( [ (x, 'todo') for tagsfile in tagsfiles ] )
853                 default_answer='d'
854             else:
855                 break
856
857         paths=""
858         paths += self.edge_dir() + " "
859         paths += build.edge_dir() + " "
860         self.run_prompt("Review module and build","svn diff " + paths)
861         self.run_prompt("Commit module and build","svn commit --file %s %s"%(changelog,paths))
862         self.run_prompt("Create tag","svn copy --file %s %s %s"%(changelog,edge_url,new_tag_url))
863
864         if self.options.debug:
865             print 'Preserving',changelog
866         else:
867             os.unlink(changelog)
868             
869 ##############################
870     def do_branch (self):
871
872         # save self.branch if any, as a hint for the new branch 
873         # do this before anything else and restore .branch to None, 
874         # as this is part of the class's logic
875         new_trunk_name=None
876         if hasattr(self,'branch'):
877             new_trunk_name=self.branch
878             del self.branch
879         elif self.options.new_version:
880             new_trunk_name = self.options.new_version
881
882         # compute diff - a way to initialize the whole stuff
883         # do_diff already does edge_dir initialization
884         # and it checks that edge_url and tag_url exist as well
885         (spec_dict,edge_url,tag_url,diff_listing) = self.do_diff(compute_only=True)
886
887         # the version name in the trunk becomes the new branch name
888         branch_name = spec_dict[self.module_version_varname]
889
890         # figure new branch name (the one for the trunk) if not provided on the command line
891         if not new_trunk_name:
892             # heuristic is to assume 'version' is a dot-separated name
893             # we isolate the rightmost part and try incrementing it by 1
894             version=spec_dict[self.module_version_varname]
895             try:
896                 m=re.compile("\A(?P<leftpart>.+)\.(?P<rightmost>[^\.]+)\Z")
897                 (leftpart,rightmost)=m.match(version).groups()
898                 incremented = int(rightmost)+1
899                 new_trunk_name="%s.%d"%(leftpart,incremented)
900             except:
901                 raise Exception, 'Cannot figure next branch name from %s - exiting'%version
902
903         # record starting point tagname
904         latest_tag_name = self.tag_name(spec_dict)
905
906         print "**********"
907         print "Using starting point %s (%s)"%(tag_url,latest_tag_name)
908         print "Creating branch %s  &  moving trunk to %s"%(branch_name,new_trunk_name)
909         print "**********"
910
911         # print warning if pending diffs
912         if diff_listing:
913             print """*** WARNING : Module %s has pending diffs on its trunk
914 It is safe to proceed, but please note that branch %s
915 will be based on latest tag %s and *not* on the current trunk"""%(self.name,branch_name,latest_tag_name)
916             while True:
917                 answer = prompt ('Are you sure you want to proceed with branching',True,('d','iff'))
918                 if answer is True:
919                     break
920                 elif answer is False:
921                     raise Exception,"User quit"
922                 elif answer == 'd':
923                     print '<<<< %s'%tag_url
924                     print '>>>> %s'%edge_url
925                     print diff_listing
926
927         branch_url = "%s/%s/branches/%s"%(Module.config['svnpath'],self.name,branch_name)
928         self.check_svnpath_not_exists (branch_url,"new branch")
929         
930         # patching trunk
931         spec_dict[self.module_version_varname]=new_trunk_name
932         spec_dict[self.module_taglevel_varname]='0'
933         # remember this in the trunk for easy location of the current branch
934         spec_dict['module_current_branch']=branch_name
935         self.patch_spec_var(spec_dict,True)
936         
937         # create commit log file
938         tmp="/tmp/branching-%d"%os.getpid()
939         f=open(tmp,"w")
940         f.write("Branch %s for module %s created (as new trunk) from tag %s\n"%(new_trunk_name,self.name,latest_tag_name))
941         f.close()
942
943         # we're done, let's commit the stuff
944         command="svn diff %s"%self.edge_dir()
945         self.run_prompt("Review changes in trunk",command)
946         command="svn copy --file %s %s %s"%(tmp,self.edge_url(),branch_url)
947         self.run_prompt("Create branch",command)
948         command="svn commit --file %s %s"%(tmp,self.edge_dir())
949         self.run_prompt("Commit trunk",command)
950         new_tag_url=self.tag_url(spec_dict)
951         command="svn copy --file %s %s %s"%(tmp,self.edge_url(),new_tag_url)
952         self.run_prompt("Create initial tag in trunk",command)
953         os.unlink(tmp)
954
955 ##############################
956 class Package:
957
958     def __init__(self, package, module, svnpath, spec):
959         self.package=package
960         self.module=module
961         self.svnpath=svnpath
962         self.spec=spec
963         self.specpath="%s/%s"%(svnpath,spec)
964         self.basename=os.path.basename(svnpath)
965
966     # returns a http URL to the trac path where full diff can be viewed (between self and pkg)
967     # typically http://svn.planet-lab.org/changeset?old_path=Monitor%2Ftags%2FMonitor-1.0-7&new_path=Monitor%2Ftags%2FMonitor-1.0-13
968     # xxx quick & dirty: rough url parsing 
969     def trac_full_diff (self, pkg):
970         matcher=re.compile("\A(?P<method>.*)://(?P<hostname>[^/]+)/(svn/)?(?P<path>.*)\Z")
971         self_match=matcher.match(self.svnpath)
972         pkg_match=matcher.match(pkg.svnpath)
973         if self_match and pkg_match:
974             (method,hostname,svn,path)=self_match.groups()
975             self_path=path.replace("/","%2F")
976             pkg_path=pkg_match.group('path').replace("/","%2F")
977             return "%s://%s/changeset?old_path=%s&new_path=%s"%(method,hostname,self_path,pkg_path)
978         else:
979             return None
980
981     def details (self):
982         return "[%s %s] [%s (spec)]"%(self.svnpath,self.basename,self.specpath)
983
984 class Build (Module):
985     
986     # we cannot get build's svnpath as for other packages as we'd get something in svn+ssh
987     # xxx quick & dirty
988     def __init__ (self, buildtag,options):
989         self.buildtag=buildtag
990         # if the buildtag start with a : (to use a branch rather than a tag)
991         if buildtag.find(':') == 0 : 
992             module_name="build%(buildtag)s"%locals()
993             self.display=buildtag[1:]
994             self.svnpath="http://svn.planet-lab.org/svn/build/branches/%s"%self.display
995         else : 
996             module_name="build@%(buildtag)s"%locals()
997             self.display=buildtag
998             self.svnpath="http://svn.planet-lab.org/svn/build/tags/%s"%self.buildtag
999         Module.__init__(self,module_name,options)
1000
1001     @staticmethod
1002     def get_distro_from_distrotag (distrotag):
1003         # mhh: remove -tag* from distrotags to get distro
1004         n=distrotag.find('-tag')
1005         if n>0:
1006             return distrotag[:n]
1007         else:
1008             return None
1009
1010     def get_packages (self,distrotag):
1011         result={}
1012         distro=Build.get_distro_from_distrotag(distrotag)
1013         if not distro:
1014             return result
1015         make_options="--no-print-directory -C %s stage1=true PLDISTRO=%s PLDISTROTAGS=%s 2> /dev/null"%(self.edge_dir(),distro,distrotag)
1016         command="make %s packages"%make_options
1017         make_packages=Command(command,self.options).output_of()
1018         pkg_line=re.compile("\Apackage=(?P<package>[^\s]+)\s+ref_module=(?P<module>[^\s]+)\s.*\Z")
1019         for line in make_packages.split("\n"):
1020             if not line:
1021                 continue
1022             attempt=pkg_line.match(line)
1023             if line and not attempt:
1024                 print "====="
1025                 print "WARNING: line not understood from make packages"
1026                 print "in dir %s"%self.edge_dir
1027                 print "with options",make_options
1028                 print 'line=',line
1029                 print "====="
1030             else:
1031                 (package,module) = (attempt.group('package'),attempt.group('module')) 
1032                 command="make %s +%s-SVNPATH"%(make_options,module)
1033                 svnpath=Command(command,self.options).output_of().strip()
1034                 command="make %s +%s-SPEC"%(make_options,package)
1035                 spec=Command(command,self.options).output_of().strip()
1036                 result[package]=Package(package,module,svnpath,spec)
1037         return result
1038
1039     def get_distrotags (self):
1040         return [os.path.basename(p) for p in glob("%s/*tags*mk"%self.edge_dir())]
1041
1042 class DiffCache:
1043
1044     def __init__ (self):
1045         self._cache={}
1046
1047     def key(self, frompath,topath):
1048         return frompath+'-to-'+topath
1049
1050     def fetch (self, frompath, topath):
1051         key=self.key(frompath,topath)
1052         if not self._cache.has_key(key):
1053             return None
1054         return self._cache[key]
1055
1056     def store (self, frompath, topath, diff):
1057         key=self.key(frompath,topath)
1058         self._cache[key]=diff
1059
1060 class Release:
1061
1062     # header in diff output
1063     discard_matcher=re.compile("\A(\+\+\+|---).*")
1064
1065     @staticmethod
1066     def do_changelog (buildtag_new,buildtag_old,options):
1067         print "----"
1068         print "----"
1069         print "----"
1070         (build_new,build_old) = (Build (buildtag_new,options), Build (buildtag_old,options))
1071         print "= build tag %s to %s = #build-%s"%(build_old.display,build_new.display,build_new.display)
1072         for b in (build_new,build_old):
1073             b.init_module_dir()
1074             b.init_edge_dir()
1075             b.update_edge_dir()
1076         # find out the tags files that are common, unless option was specified
1077         if options.distrotags:
1078             distrotags=options.distrotags
1079         else:
1080             distrotags_new=build_new.get_distrotags()
1081             distrotags_old=build_old.get_distrotags()
1082             distrotags = list(set(distrotags_new).intersection(set(distrotags_old)))
1083             distrotags.sort()
1084         if options.verbose: print "Found distrotags",distrotags
1085         first_distrotag=True
1086         diffcache = DiffCache()
1087         for distrotag in distrotags:
1088             distro=Build.get_distro_from_distrotag(distrotag)
1089             if not distro:
1090                 continue
1091             if first_distrotag:
1092                 first_distrotag=False
1093             else:
1094                 print '----'
1095             print '== distro %s (%s to %s) == #distro-%s-%s'%(distrotag,build_old.display,build_new.display,distro,build_new.display)
1096             print ' * from %s/%s'%(build_old.svnpath,distrotag)
1097             print ' * to %s/%s'%(build_new.svnpath,distrotag)
1098
1099             # parse make packages
1100             packages_new=build_new.get_packages(distrotag)
1101             pnames_new=set(packages_new.keys())
1102             if options.verbose: print 'got packages for ',build_new.display
1103             packages_old=build_old.get_packages(distrotag)
1104             pnames_old=set(packages_old.keys())
1105             if options.verbose: print 'got packages for ',build_old.display
1106
1107             # get created, deprecated, and preserved package names
1108             pnames_created = list(pnames_new-pnames_old)
1109             pnames_created.sort()
1110             pnames_deprecated = list(pnames_old-pnames_new)
1111             pnames_deprecated.sort()
1112             pnames = list(pnames_new.intersection(pnames_old))
1113             pnames.sort()
1114
1115             if options.verbose: print "Found new/deprecated/preserved pnames",pnames_new,pnames_deprecated,pnames
1116
1117             # display created and deprecated 
1118             for name in pnames_created:
1119                 print '=== %s : new package %s -- appeared in %s === #package-%s-%s-%s'%(
1120                     distrotag,name,build_new.display,name,distro,build_new.display)
1121                 pobj=packages_new[name]
1122                 print ' * %s'%pobj.details()
1123             for name in pnames_deprecated:
1124                 print '=== %s : package %s -- deprecated, last occurrence in %s === #package-%s-%s-%s'%(
1125                     distrotag,name,build_old.display,name,distro,build_new.display)
1126                 pobj=packages_old[name]
1127                 if not pobj.svnpath:
1128                     print ' * codebase stored in CVS, specfile is %s'%pobj.spec
1129                 else:
1130                     print ' * %s'%pobj.details()
1131
1132             # display other packages
1133             for name in pnames:
1134                 (pobj_new,pobj_old)=(packages_new[name],packages_old[name])
1135                 if options.verbose: print "Dealing with package",name
1136                 if pobj_old.specpath == pobj_new.specpath:
1137                     continue
1138                 specdiff = diffcache.fetch(pobj_old.specpath,pobj_new.specpath)
1139                 if specdiff is None:
1140                     command="svn diff %s %s"%(pobj_old.specpath,pobj_new.specpath)
1141                     specdiff=Command(command,options).output_of()
1142                     diffcache.store(pobj_old.specpath,pobj_new.specpath,specdiff)
1143                 else:
1144                     if options.verbose: print 'got diff from cache'
1145                 if not specdiff:
1146                     continue
1147                 print '=== %s - %s to %s : package %s === #package-%s-%s-%s'%(
1148                     distrotag,build_old.display,build_new.display,name,name,distro,build_new.display)
1149                 print ' * from %s to %s'%(pobj_old.details(),pobj_new.details())
1150                 trac_diff_url=pobj_old.trac_full_diff(pobj_new)
1151                 if trac_diff_url:
1152                     print ' * [%s View full diff]'%trac_diff_url
1153                 print '{{{'
1154                 for line in specdiff.split('\n'):
1155                     if not line:
1156                         continue
1157                     if Release.discard_matcher.match(line):
1158                         continue
1159                     if line[0] in ['@']:
1160                         print '----------'
1161                     elif line[0] in ['+','-']:
1162                         print_fold(line)
1163                 print '}}}'
1164
1165 ##############################
1166 class Main:
1167
1168     module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1169 module-tools : a set of tools to manage subversion tags and specfile
1170   requires the specfile to either
1171   * define *version* and *taglevel*
1172   OR alternatively 
1173   * define redirection variables module_version_varname / module_taglevel_varname
1174 Trunk:
1175   by default, the trunk of modules is taken into account
1176   in this case, just mention the module name as <module_desc>
1177 Branches:
1178   if you wish to work on a branch rather than on the trunk, 
1179   you can use something like e.g. Mom:2.1 as <module_desc>
1180 """
1181     release_usage="""Usage: %prog [options] tag1 .. tagn
1182   Extract release notes from the changes in specfiles between several build tags, latest first
1183   Examples:
1184       release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1185   You can refer to a (build) branch by prepending a colon, like in
1186       release-changelog :4.2 4.2-rc25
1187 """
1188     common_usage="""More help:
1189   see http://svn.planet-lab.org/wiki/ModuleTools"""
1190
1191     modes={ 
1192         'list' : "displays a list of available tags or branches",
1193         'version' : "check latest specfile and print out details",
1194         'diff' : "show difference between module (trunk or branch) and latest tag",
1195         'tag'  : """increment taglevel in specfile, insert changelog in specfile,
1196                 create new tag and and monitor its adoption in build/*-tags*.mk""",
1197         'branch' : """create a branch for this module, from the latest tag on the trunk, 
1198                   and change trunk's version number to reflect the new branch name;
1199                   you can specify the new branch name by using module:branch""",
1200         'sync' : """create a tag from the module
1201                 this is a last resort option, mostly for repairs""",
1202         'changelog' : """extract changelog between build tags
1203                 expected arguments are a list of tags""",
1204         }
1205
1206     silent_modes = ['list']
1207     release_modes = ['changelog']
1208
1209     @staticmethod
1210     def optparse_list (option, opt, value, parser):
1211         try:
1212             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1213         except:
1214             setattr(parser.values,option.dest,value.split())
1215
1216     def run(self):
1217
1218         mode=None
1219         for function in Main.modes.keys():
1220             if sys.argv[0].find(function) >= 0:
1221                 mode = function
1222                 break
1223         if not mode:
1224             print "Unsupported command",sys.argv[0]
1225             print "Supported commands:" + Modes.modes.keys.join(" ")
1226             sys.exit(1)
1227
1228         if mode not in Main.release_modes:
1229             usage = Main.module_usage
1230             usage += Main.common_usage
1231             usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1232         else:
1233             usage = Main.release_usage
1234             usage += Main.common_usage
1235
1236         parser=OptionParser(usage=usage,version=subversion_id)
1237         
1238         if mode == 'list':
1239             parser.add_option("-b","--branches",action="store_true",dest="list_branches",default=False,
1240                               help="list branches")
1241             parser.add_option("-t","--tags",action="store_false",dest="list_branches",
1242                               help="list tags")
1243             parser.add_option("-m","--match",action="store",dest="list_pattern",default=None,
1244                                help="grep pattern for filtering output")
1245             parser.add_option("-x","--exact-match",action="store",dest="list_exact",default=None,
1246                                help="exact grep pattern for filtering output")
1247         if mode == "tag" or mode == 'branch':
1248             parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1249                               help="set new version and reset taglevel to 0")
1250         if mode == "tag" :
1251             parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1252                               help="do not update changelog section in specfile when tagging")
1253             parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1254                               help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1255         if mode == "tag" or mode == "sync" :
1256             parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1257                               help="specify editor")
1258         if mode == "sync" :
1259             parser.add_option("-m","--message", action="store", dest="message", default=None,
1260                               help="specify log message")
1261         if mode == "diff" :
1262             parser.add_option("-W","--www", action="store", dest="www", default=False,
1263                               help="export diff in html format, e.g. -W trunk")
1264         if mode == "diff" :
1265             parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1266                               help="just list modules that exhibit differences")
1267
1268         if mode  == 'version':
1269             parser.add_option("-u","--url", action="store_true", dest="show_urls", default=False,
1270                               help="display URLs")
1271             
1272         default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1273         if mode not in Main.release_modes:
1274             parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1275                               help="run on all modules as found in %s"%default_modules_list)
1276             parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1277                               help="run on all modules found in specified file")
1278         else:
1279             parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1280                               help="dry run - shell commands are only displayed")
1281             parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1282                               default=[], nargs=1,type="string",
1283                               help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1284 -- can be set multiple times, or use quotes""")
1285
1286         parser.add_option("-w","--workdir", action="store", dest="workdir", 
1287                           default="%s/%s"%(os.getenv("HOME"),"modules"),
1288                           help="""name for dedicated working dir - defaults to ~/modules
1289 ** THIS MUST NOT ** be your usual working directory""")
1290         parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1291                           help="skip safety checks, such as svn updates -- use with care")
1292
1293         # default verbosity depending on function - temp
1294         verbose_modes= ['tag','sync']
1295         
1296         if mode not in verbose_modes:
1297             parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
1298                               help="run in verbose mode")
1299         else:
1300             parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1301                               help="run in quiet (non-verbose) mode")
1302 #        parser.add_option("-d","--debug", action="store_true", dest="debug", default=False, 
1303 #                          help="debug mode - mostly more verbose")
1304         (options, args) = parser.parse_args()
1305         options.mode=mode
1306         if not hasattr(options,'dry_run'):
1307             options.dry_run=False
1308         if not hasattr(options,'www'):
1309             options.www=False
1310         options.debug=False
1311
1312         ########## release-*
1313         if mode in Main.release_modes :
1314             ########## changelog
1315             if len(args) <= 1:
1316                 parser.print_help()
1317                 sys.exit(1)
1318             Module.init_homedir(options)
1319             for n in range(len(args)-1):
1320                 [t_new,t_old]=args[n:n+2]
1321                 Release.do_changelog (t_new,t_old,options)
1322         else:
1323             ########## module-*
1324             if len(args) == 0:
1325                 if options.all_modules:
1326                     options.modules_list=default_modules_list
1327                 if options.modules_list:
1328                     args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1329                 else:
1330                     parser.print_help()
1331                     sys.exit(1)
1332             Module.init_homedir(options)
1333
1334             # 2 passes for www output
1335             modules=[ Module(modname,options) for modname in args ]
1336             # hack: create a dummy Module to store errors/warnings
1337             error_module = Module('__errors__',options)
1338
1339             # pass 1 : do it, except if options.www
1340             for module in modules:
1341                 if len(args)>1 and mode not in Main.silent_modes and not options.www:
1342                     print '========================================',module.friendly_name()
1343                 # call the method called do_<mode>
1344                 method=Module.__dict__["do_%s"%mode]
1345                 try:
1346                     method(module)
1347                 except Exception,e:
1348                     if options.www:
1349                         title='<span class="error"> Skipping module %s - failure: %s </span>'%(module.name, str(e))
1350                         error_module.html_store_title(title)
1351                     else:
1352                         print 'Skipping module %s: '%modname,e
1353
1354             # in which case we do the actual printing in the second pass
1355             if options.www:
1356                 modules.append(error_module)
1357                 error_module.html_dump_header()
1358                 for module in modules:
1359                     module.html_dump_toc()
1360                 Module.html_dump_middle()
1361                 for module in modules:
1362                     module.html_dump_body()
1363                 Module.html_dump_footer()
1364
1365 ####################
1366 if __name__ == "__main__" :
1367     try:
1368         Main().run()
1369     except KeyboardInterrupt:
1370         print '\nBye'