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