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