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