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