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