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