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