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