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