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