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