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