force adoption of tags are more strict
[build.git] / module-tools.py
1 #!/usr/bin/python -u
2
3 import sys, os
4 import re
5 import time
6 from glob import glob
7 from optparse import OptionParser
8
9 # HARDCODED NAME CHANGES
10 #
11 # Moving to git we decided to rename some of the repositories. Here is
12 # a map of name changes applied in git repositories.
13 RENAMED_SVN_MODULES = {
14     "PLEWWW": "plewww",
15     "PLCAPI": "plcapi",
16     "BootManager": "bootmanager",
17     "BootCD": "bootcd",
18     "VserverReference": "vserver-reference",
19     "BootstrapFS": "bootstrapfs",
20     "MyPLC": "myplc",
21     "CoDemux": "codemux",
22     "NodeManager": "nodemanager",
23     "NodeUpdate": "nodeupdate"
24     }
25
26 def svn_to_git_name(module):
27     if RENAMED_SVN_MODULES.has_key(module):
28         return RENAMED_SVN_MODULES[module]
29     return module
30
31 def git_to_svn_name(module):
32     for key in RENAMED_SVN_MODULES:
33         if module == RENAMED_SVN_MODULES[key]:
34             return key
35     return module
36     
37
38 # e.g. other_choices = [ ('d','iff') , ('g','uess') ] - lowercase 
39 def prompt (question,default=True,other_choices=[],allow_outside=False):
40     if not isinstance (other_choices,list):
41         other_choices = [ other_choices ]
42     chars = [ c for (c,rest) in other_choices ]
43
44     choices = []
45     if 'y' not in chars:
46         if default is True: choices.append('[y]')
47         else : choices.append('y')
48     if 'n' not in chars:
49         if default is False: choices.append('[n]')
50         else : choices.append('n')
51
52     for (char,choice) in other_choices:
53         if default == char:
54             choices.append("["+char+"]"+choice)
55         else:
56             choices.append("<"+char+">"+choice)
57     try:
58         answer=raw_input(question + " " + "/".join(choices) + " ? ")
59         if not answer:
60             return default
61         answer=answer[0].lower()
62         if answer == 'y':
63             if 'y' in chars: return 'y'
64             else: return True
65         elif answer == 'n':
66             if 'n' in chars: return 'n'
67             else: return False
68         elif other_choices:
69             for (char,choice) in other_choices:
70                 if answer == char:
71                     return char
72             if allow_outside:
73                 return answer
74         return prompt(question,default,other_choices)
75     except:
76         raise
77
78 def default_editor():
79     try:
80         editor = os.environ['EDITOR']
81     except:
82         editor = "emacs"
83     return editor
84
85 ### fold long lines
86 fold_length=132
87
88 def print_fold (line):
89     while len(line) >= fold_length:
90         print line[:fold_length],'\\'
91         line=line[fold_length:]
92     print line
93
94 class Command:
95     def __init__ (self,command,options):
96         self.command=command
97         self.options=options
98         self.tmp="/tmp/command-%d"%os.getpid()
99
100     def run (self):
101         if self.options.dry_run:
102             print 'dry_run',self.command
103             return 0
104         if self.options.verbose and self.options.mode not in Main.silent_modes:
105             print '+',self.command
106             sys.stdout.flush()
107         return os.system(self.command)
108
109     def run_silent (self):
110         if self.options.dry_run:
111             print 'dry_run',self.command
112             return 0
113         if self.options.verbose:
114             print '+',self.command,' .. ',
115             sys.stdout.flush()
116         retcod=os.system(self.command + " &> " + self.tmp)
117         if retcod != 0:
118             print "FAILED ! -- out+err below (command was %s)"%self.command
119             os.system("cat " + self.tmp)
120             print "FAILED ! -- end of quoted output"
121         elif self.options.verbose:
122             print "OK"
123         os.unlink(self.tmp)
124         return retcod
125
126     def run_fatal(self):
127         if self.run_silent() !=0:
128             raise Exception,"Command %s failed"%self.command
129
130     # returns stdout, like bash's $(mycommand)
131     def output_of (self,with_stderr=False):
132         if self.options.dry_run:
133             print 'dry_run',self.command
134             return 'dry_run output'
135         tmp="/tmp/status-%d"%os.getpid()
136         if self.options.debug:
137             print '+',self.command,' .. ',
138             sys.stdout.flush()
139         command=self.command
140         if with_stderr:
141             command += " &> "
142         else:
143             command += " > "
144         command += tmp
145         os.system(command)
146         result=file(tmp).read()
147         os.unlink(tmp)
148         if self.options.debug:
149             print 'Done',
150         return result
151
152
153 class SvnRepository:
154     type = "svn"
155
156     def __init__(self, path, options):
157         self.path = path
158         self.options = options
159
160     def name(self):
161         return os.path.basename(self.path)
162
163     def url(self):
164         out = Command("svn info %s" % self.path, self.options).output_of()
165         for line in out.split('\n'):
166             if line.startswith("URL:"):
167                 return line.split()[1].strip()
168
169     def repo_root(self):
170         out = Command("svn info %s" % self.path, self.options).output_of()
171         for line in out.split('\n'):
172             if line.startswith("Repository Root:"):
173                 root = line.split()[2].strip()
174                 return "%s/%s" % (root, self.name())
175
176     @classmethod
177     def checkout(cls, remote, local, options, recursive=False):
178         if recursive:
179             svncommand = "svn co %s %s" % (remote, local)
180         else:
181             svncommand = "svn co -N %s %s" % (remote, local)
182         Command("rm -rf %s" % local, options).run_silent()
183         Command(svncommand, options).run_fatal()
184
185         return SvnRepository(local, options)
186
187     @classmethod
188     def remote_exists(cls, remote):
189         return os.system("svn list %s &> /dev/null" % remote) == 0
190
191     def tag_exists(self, tagname):
192         url = "%s/tags/%s" % (self.repo_root(), tagname)
193         return SvnRepository.remote_exists(url)
194
195     def update(self, subdir="", recursive=True, branch=None):
196         path = os.path.join(self.path, subdir)
197         if recursive:
198             svncommand = "svn up %s" % path
199         else:
200             svncommand = "svn up -N %s" % path
201         Command(svncommand, self.options).run_fatal()
202
203     def commit(self, logfile):
204         # add all new files to the repository
205         Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs svn add" %
206                 self.path, self.options).output_of()
207         Command("svn commit -F %s %s" % (logfile, self.path), self.options).run_fatal()
208
209     def to_branch(self, branch):
210         remote = "%s/branches/%s" % (self.repo_root(), branch)
211         SvnRepository.checkout(remote, self.path, self.options, recursive=True)
212
213     def to_tag(self, tag):
214         remote = "%s/tags/%s" % (self.repo_root(), branch)
215         SvnRepository.checkout(remote, self.path, self.options, recursive=True)
216
217     def tag(self, tagname, logfile):
218         tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
219         self_url = self.url()
220         Command("svn copy -F %s %s %s" % (logfile, self_url, tag_url), self.options).run_fatal()
221
222     def diff(self, f=""):
223         if f:
224             f = os.path.join(self.path, f)
225         else:
226             f = self.path
227         return Command("svn diff %s" % f, self.options).output_of(True)
228
229     def diff_with_tag(self, tagname):
230         tag_url = "%s/tags/%s" % (self.repo_root(), tagname)
231         return Command("svn diff %s %s" % (tag_url, self.url()),
232                        self.options).output_of(True)
233
234     def revert(self, f=""):
235         if f:
236             Command("svn revert %s" % os.path.join(self.path, f), self.options).run_fatal()
237         else:
238             # revert all
239             Command("svn revert %s -R" % self.path, self.options).run_fatal()
240             Command("svn status %s | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\\ /g' | xargs rm -rf " %
241                     self.path, self.options).run_silent()
242
243     def is_clean(self):
244         command="svn status %s" % self.path
245         return len(Command(command,self.options).output_of(True)) == 0
246
247     def is_valid(self):
248         return os.path.exists(os.path.join(self.path, ".svn"))
249     
250
251 class GitRepository:
252     type = "git"
253
254     def __init__(self, path, options):
255         self.path = path
256         self.options = options
257
258     def name(self):
259         return os.path.basename(self.path)
260
261     def url(self):
262         return self.repo_root()
263
264     def repo_root(self):
265         c = Command("git remote show origin", self.options)
266         out = self.__run_in_repo(c.output_of)
267         for line in out.split('\n'):
268             if line.strip().startswith("Fetch URL:"):
269                 return line.split()[2]
270
271     @classmethod
272     def checkout(cls, remote, local, options, depth=0):
273         Command("rm -rf %s" % local, options).run_silent()
274         Command("git clone --depth %d %s %s" % (depth, remote, local), options).run_fatal()
275         return GitRepository(local, options)
276
277     @classmethod
278     def remote_exists(cls, remote):
279         return os.system("git --no-pager ls-remote %s &> /dev/null" % remote) == 0
280
281     def tag_exists(self, tagname):
282         command = 'git tag -l | grep "^%s$"' % tagname
283         c = Command(command, self.options)
284         out = self.__run_in_repo(c.output_of, with_stderr=True)
285         return len(out) > 0
286
287     def __run_in_repo(self, fun, *args, **kwargs):
288         cwd = os.getcwd()
289         os.chdir(self.path)
290         ret = fun(*args, **kwargs)
291         os.chdir(cwd)
292         return ret
293
294     def __run_command_in_repo(self, command, ignore_errors=False):
295         c = Command(command, self.options)
296         if ignore_errors:
297             return self.__run_in_repo(c.output_of)
298         else:
299             return self.__run_in_repo(c.run_fatal)
300
301     def __is_commit_id(self, id):
302         c = Command("git show %s | grep commit | awk '{print $2;}'" % id, self.options)
303         ret = self.__run_in_repo(c.output_of, with_stderr=False)
304         if ret.strip() == id:
305             return True
306         return False
307
308     def update(self, subdir=None, recursive=None, branch="master"):
309         if branch == "master":
310             self.__run_command_in_repo("git checkout %s" % branch)
311         else:
312             self.to_branch(branch, remote=True)
313         self.__run_command_in_repo("git fetch origin --tags")
314         self.__run_command_in_repo("git fetch origin")
315         if not self.__is_commit_id(branch):
316             # we don't need to merge anythign for commit ids.
317             self.__run_command_in_repo("git merge --ff origin/%s" % branch)
318
319     def to_branch(self, branch, remote=True):
320         self.revert()
321         if remote:
322             command = "git branch --track %s origin/%s" % (branch, branch)
323             c = Command(command, self.options)
324             self.__run_in_repo(c.output_of, with_stderr=True)
325         return self.__run_command_in_repo("git checkout %s" % branch)
326
327     def to_tag(self, tag):
328         self.revert()
329         return self.__run_command_in_repo("git checkout %s" % tag)
330
331     def tag(self, tagname, logfile):
332         self.__run_command_in_repo("git tag %s -F %s" % (tagname, logfile))
333         self.commit(logfile)
334
335     def diff(self, f=""):
336         c = Command("git diff %s" % f, self.options)
337         return self.__run_in_repo(c.output_of, with_stderr=True)
338
339     def diff_with_tag(self, tagname):
340         c = Command("git diff %s" % tagname, self.options)
341         return self.__run_in_repo(c.output_of, with_stderr=True)
342
343     def commit(self, logfile, branch="master"):
344         self.__run_command_in_repo("git add .", ignore_errors=True)
345         self.__run_command_in_repo("git add -u", ignore_errors=True)
346         self.__run_command_in_repo("git commit -F  %s" % logfile, ignore_errors=True)
347         if branch == "master" or self.__is_commit_id(branch):
348             self.__run_command_in_repo("git push")
349         else:
350             self.__run_command_in_repo("git push origin %s:%s" % (branch, branch))
351         self.__run_command_in_repo("git push --tags")
352
353     def revert(self, f=""):
354         if f:
355             self.__run_command_in_repo("git checkout %s" % f)
356         else:
357             # revert all
358             self.__run_command_in_repo("git --no-pager reset --hard")
359             self.__run_command_in_repo("git --no-pager clean -f")
360
361     def is_clean(self):
362         def check_commit():
363             command="git status"
364             s="nothing to commit (working directory clean)"
365             return Command(command, self.options).output_of(True).find(s) >= 0
366         return self.__run_in_repo(check_commit)
367
368     def is_valid(self):
369         return os.path.exists(os.path.join(self.path, ".git"))
370     
371
372 class Repository:
373     """ Generic repository """
374     supported_repo_types = [SvnRepository, GitRepository]
375
376     def __init__(self, path, options):
377         self.path = path
378         self.options = options
379         for repo in self.supported_repo_types:
380             self.repo = repo(self.path, self.options)
381             if self.repo.is_valid():
382                 break
383
384     @classmethod
385     def has_moved_to_git(cls, module, config):
386         module = svn_to_git_name(module)
387         # check if the module is already in Git
388 #        return SvnRepository.remote_exists("%s/%s/aaaa-has-moved-to-git" % (config['svnpath'], module))
389         return GitRepository.remote_exists(Module.git_remote_dir(module))
390
391
392     @classmethod
393     def remote_exists(cls, remote):
394         for repo in Repository.supported_repo_types:
395             if repo.remote_exists(remote):
396                 return True
397         return False
398
399     def __getattr__(self, attr):
400         return getattr(self.repo, attr)
401
402
403
404 # support for tagged module is minimal, and is for the Build class only
405 class Module:
406
407     svn_magic_line="--This line, and those below, will be ignored--"
408     setting_tag_format = "Setting tag %s"
409     
410     redirectors=[ # ('module_name_varname','name'),
411                   ('module_version_varname','version'),
412                   ('module_taglevel_varname','taglevel'), ]
413
414     # where to store user's config
415     config_storage="CONFIG"
416     # 
417     config={}
418
419     import commands
420     configKeys=[ ('svnpath',"Enter your toplevel svnpath",
421                   "svn+ssh://%s@svn.planet-lab.org/svn/"%commands.getoutput("id -un")),
422                  ('gitserver', "Enter your git server's hostname", "git.onelab.eu"),
423                  ('gituser', "Enter your user name (login name) on git server", commands.getoutput("id -un")),
424                  ("build", "Enter the name of your build module","build"),
425                  ('username',"Enter your firstname and lastname for changelogs",""),
426                  ("email","Enter your email address for changelogs",""),
427                  ]
428
429     @classmethod
430     def prompt_config_option(cls, key, message, default):
431         cls.config[key]=raw_input("%s [%s] : "%(message,default)).strip() or default
432
433     @classmethod
434     def prompt_config (cls):
435         for (key,message,default) in cls.configKeys:
436             cls.config[key]=""
437             while not cls.config[key]:
438                 cls.prompt_config_option(key, message, default)
439
440
441     # for parsing module spec name:branch
442     matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
443     # special form for tagged module - for Build
444     matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
445     # parsing specfiles
446     matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
447
448     def __init__ (self,module_spec,options):
449         # parse module spec
450         attempt=Module.matcher_branch_spec.match(module_spec)
451         if attempt:
452             self.name=attempt.group('name')
453             self.branch=attempt.group('branch')
454         else:
455             attempt=Module.matcher_tag_spec.match(module_spec)
456             if attempt:
457                 self.name=attempt.group('name')
458                 self.tagname=attempt.group('tagname')
459             else:
460                 self.name=module_spec
461
462         # when available prefer to use git module name internally
463         self.name = svn_to_git_name(self.name)
464
465         self.options=options
466         self.module_dir="%s/%s"%(options.workdir,self.name)
467         self.repository = None
468         self.build = None
469
470     def run (self,command):
471         return Command(command,self.options).run()
472     def run_fatal (self,command):
473         return Command(command,self.options).run_fatal()
474     def run_prompt (self,message,fun, *args):
475         fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
476         if not self.options.verbose:
477             while True:
478                 choice=prompt(message,True,('s','how'))
479                 if choice is True:
480                     fun(*args)
481                     return
482                 elif choice is False:
483                     print 'About to run function:', fun_msg
484         else:
485             question=message+" - want to run function: " + fun_msg
486             if prompt(question,True):
487                 fun(*args)
488
489     def friendly_name (self):
490         if hasattr(self,'branch'):
491             return "%s:%s"%(self.name,self.branch)
492         elif hasattr(self,'tagname'):
493             return "%s@%s"%(self.name,self.tagname)
494         else:
495             return self.name
496
497     @classmethod
498     def git_remote_dir (cls, name):
499         return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
500
501     @classmethod
502     def svn_remote_dir (cls, name):
503         name = git_to_svn_name(name)
504         svn = cls.config['svnpath']
505         if svn.endswith('/'):
506             return "%s%s" % (svn, name)
507         return "%s/%s" % (svn, name)
508
509     def svn_selected_remote(self):
510         svn_name = git_to_svn_name(self.name)
511         remote = self.svn_remote_dir(svn_name)
512         if hasattr(self,'branch'):
513             remote = "%s/branches/%s" % (remote, self.branch)
514         elif hasattr(self,'tagname'):
515             remote = "%s/tags/%s" % (remote, self.tagname)
516         else:
517             remote = "%s/trunk" % remote
518         return remote
519
520     ####################
521     @classmethod
522     def init_homedir (cls, options):
523         if options.verbose and options.mode not in Main.silent_modes:
524             print 'Checking for', options.workdir
525         storage="%s/%s"%(options.workdir, cls.config_storage)
526         # sanity check. Either the topdir exists AND we have a config/storage
527         # or topdir does not exist and we create it
528         # to avoid people use their own daily svn repo
529         if os.path.isdir(options.workdir) and not os.path.isfile(storage):
530             print """The directory %s exists and has no CONFIG file
531 If this is your regular working directory, please provide another one as the
532 module-* commands need a fresh working dir. Make sure that you do not use 
533 that for other purposes than tagging""" % options.workdir
534             sys.exit(1)
535
536         def checkout_build():
537             print "Checking out build module..."
538             remote = cls.git_remote_dir(cls.config['build'])
539             local = os.path.join(options.workdir, cls.config['build'])
540             GitRepository.checkout(remote, local, options, depth=1)
541             print "OK"
542
543         def store_config():
544             f=file(storage,"w")
545             for (key,message,default) in Module.configKeys:
546                 f.write("%s=%s\n"%(key,Module.config[key]))
547             f.close()
548             if options.debug:
549                 print 'Stored',storage
550                 Command("cat %s"%storage,options).run()
551
552         def read_config():
553             # read config
554             f=open(storage)
555             for line in f.readlines():
556                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
557                 Module.config[key]=value                
558             f.close()
559
560         if not os.path.isdir (options.workdir):
561             print "Cannot find",options.workdir,"let's create it"
562             Command("mkdir -p %s" % options.workdir, options).run_silent()
563             cls.prompt_config()
564             checkout_build()
565             store_config()
566         else:
567             read_config()
568             # check missing config options
569             old_layout = False
570             for (key,message,default) in cls.configKeys:
571                 if not Module.config.has_key(key):
572                     print "Configuration changed for module-tools"
573                     cls.prompt_config_option(key, message, default)
574                     old_layout = True
575                     
576             if old_layout:
577                 Command("rm -rf %s" % options.workdir, options).run_silent()
578                 Command("mkdir -p %s" % options.workdir, options).run_silent()
579                 checkout_build()
580                 store_config()
581
582             build_dir = os.path.join(options.workdir, cls.config['build'])
583             if not os.path.isdir(build_dir):
584                 checkout_build()
585             else:
586                 build = Repository(build_dir, options)
587                 if not build.is_clean():
588                     print "build module needs a revert"
589                     build.revert()
590                     print "OK"
591                 build.update()
592
593         if options.verbose and options.mode not in Main.silent_modes:
594             print '******** Using config'
595             for (key,message,default) in Module.configKeys:
596                 print '\t',key,'=',Module.config[key]
597
598     def init_module_dir (self):
599         if self.options.verbose:
600             print 'Checking for',self.module_dir
601
602         if not os.path.isdir (self.module_dir):
603             if Repository.has_moved_to_git(self.name, Module.config):
604                 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
605                                                          self.module_dir,
606                                                          self.options)
607             else:
608                 remote = self.svn_selected_remote()
609                 self.repository = SvnRepository.checkout(remote,
610                                                          self.module_dir,
611                                                          self.options, recursive=False)
612
613         self.repository = Repository(self.module_dir, self.options)
614         if self.repository.type == "svn":
615             # check if module has moved to git    
616             if Repository.has_moved_to_git(self.name, Module.config):
617                 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
618                 self.init_module_dir()
619             # check if we have the required branch/tag
620             if self.repository.url() != self.svn_selected_remote():
621                 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
622                 self.init_module_dir()
623
624         elif self.repository.type == "git":
625             if hasattr(self,'branch'):
626                 self.repository.to_branch(self.branch)
627             elif hasattr(self,'tagname'):
628                 self.repository.to_tag(self.tagname)
629
630         else:
631             raise Exception, 'Cannot find %s - check module name'%self.module_dir
632
633
634     def revert_module_dir (self):
635         if self.options.fast_checks:
636             if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
637             return
638         if self.options.verbose:
639             print 'Checking whether', self.module_dir, 'needs being reverted'
640         
641         if not self.repository.is_clean():
642             self.repository.revert()
643
644     def update_module_dir (self):
645         if self.options.fast_checks:
646             if self.options.verbose: print 'Skipping update of %s' % self.module_dir
647             return
648         if self.options.verbose:
649             print 'Updating', self.module_dir
650
651         if hasattr(self,'branch'):
652             self.repository.update(branch=self.branch)
653         elif hasattr(self,'tagname'):
654             self.repository.update(branch=self.tagname)
655         else:
656             self.repository.update()
657
658     def main_specname (self):
659         attempt="%s/%s.spec"%(self.module_dir,self.name)
660         if os.path.isfile (attempt):
661             return attempt
662         pattern1="%s/*.spec"%self.module_dir
663         level1=glob(pattern1)
664         if level1:
665             return level1[0]
666         pattern2="%s/*/*.spec"%self.module_dir
667         level2=glob(pattern2)
668
669         if level2:
670             return level2[0]
671         raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
672
673     def all_specnames (self):
674         level1=glob("%s/*.spec" % self.module_dir)
675         if level1: return level1
676         level2=glob("%s/*/*.spec" % self.module_dir)
677         return level2
678
679     def parse_spec (self, specfile, varnames):
680         if self.options.verbose:
681             print 'Parsing',specfile,
682             for var in varnames:
683                 print "[%s]"%var,
684             print ""
685         result={}
686         f=open(specfile)
687         for line in f.readlines():
688             attempt=Module.matcher_rpm_define.match(line)
689             if attempt:
690                 (define,var,value)=attempt.groups()
691                 if var in varnames:
692                     result[var]=value
693         f.close()
694         if self.options.debug:
695             print 'found',len(result),'keys'
696             for (k,v) in result.iteritems():
697                 print k,'=',v
698         return result
699                 
700     # stores in self.module_name_varname the rpm variable to be used for the module's name
701     # and the list of these names in self.varnames
702     def spec_dict (self):
703         specfile=self.main_specname()
704         redirector_keys = [ varname for (varname,default) in Module.redirectors]
705         redirect_dict = self.parse_spec(specfile,redirector_keys)
706         if self.options.debug:
707             print '1st pass parsing done, redirect_dict=',redirect_dict
708         varnames=[]
709         for (varname,default) in Module.redirectors:
710             if redirect_dict.has_key(varname):
711                 setattr(self,varname,redirect_dict[varname])
712                 varnames += [redirect_dict[varname]]
713             else:
714                 setattr(self,varname,default)
715                 varnames += [ default ] 
716         self.varnames = varnames
717         result = self.parse_spec (specfile,self.varnames)
718         if self.options.debug:
719             print '2st pass parsing done, varnames=',varnames,'result=',result
720         return result
721
722     def patch_spec_var (self, patch_dict,define_missing=False):
723         for specfile in self.all_specnames():
724             # record the keys that were changed
725             changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
726             newspecfile=specfile+".new"
727             if self.options.verbose:
728                 print 'Patching',specfile,'for',patch_dict.keys()
729             spec=open (specfile)
730             new=open(newspecfile,"w")
731
732             for line in spec.readlines():
733                 attempt=Module.matcher_rpm_define.match(line)
734                 if attempt:
735                     (define,var,value)=attempt.groups()
736                     if var in patch_dict.keys():
737                         if self.options.debug:
738                             print 'rewriting %s as %s'%(var,patch_dict[var])
739                         new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
740                         changed[var]=True
741                         continue
742                 new.write(line)
743             if define_missing:
744                 for (key,was_changed) in changed.iteritems():
745                     if not was_changed:
746                         if self.options.debug:
747                             print 'rewriting missing %s as %s'%(key,patch_dict[key])
748                         new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
749             spec.close()
750             new.close()
751             os.rename(newspecfile,specfile)
752
753     # returns all lines until the magic line
754     def unignored_lines (self, logfile):
755         result=[]
756         white_line_matcher = re.compile("\A\s*\Z")
757         for logline in file(logfile).readlines():
758             if logline.strip() == Module.svn_magic_line:
759                 break
760             elif white_line_matcher.match(logline):
761                 continue
762             else:
763                 result.append(logline.strip()+'\n')
764         return result
765
766     # creates a copy of the input with only the unignored lines
767     def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
768        f=file(fileout,'w')
769        f.write(self.setting_tag_format%new_tag_name + '\n')
770        for line in self.unignored_lines(filein):
771            f.write(line)
772        f.close()
773
774     def insert_changelog (self, logfile, oldtag, newtag):
775         for specfile in self.all_specnames():
776             newspecfile=specfile+".new"
777             if self.options.verbose:
778                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
779             spec=open (specfile)
780             new=open(newspecfile,"w")
781             for line in spec.readlines():
782                 new.write(line)
783                 if re.compile('%changelog').match(line):
784                     dateformat="* %a %b %d %Y"
785                     datepart=time.strftime(dateformat)
786                     logpart="%s <%s> - %s"%(Module.config['username'],
787                                                  Module.config['email'],
788                                                  newtag)
789                     new.write(datepart+" "+logpart+"\n")
790                     for logline in self.unignored_lines(logfile):
791                         new.write("- " + logline)
792                     new.write("\n")
793             spec.close()
794             new.close()
795             os.rename(newspecfile,specfile)
796             
797     def show_dict (self, spec_dict):
798         if self.options.verbose:
799             for (k,v) in spec_dict.iteritems():
800                 print k,'=',v
801
802     def last_tag (self, spec_dict):
803         try:
804             return "%s-%s" % (spec_dict[self.module_version_varname],
805                               spec_dict[self.module_taglevel_varname])
806         except KeyError,err:
807             raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
808
809     def tag_name (self, spec_dict, old_svn_name=False):
810         base_tag_name = self.name
811         if old_svn_name:
812             base_tag_name = git_to_svn_name(self.name)
813         return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
814     
815
816 ##############################
817     # using fine_grain means replacing only those instances that currently refer to this tag
818     # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
819     def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
820         newtagsfile=tagsfile+".new"
821         tags=open (tagsfile)
822         new=open(newtagsfile,"w")
823
824         matches=0
825         # fine-grain : replace those lines that refer to oldname
826         if fine_grain:
827             if self.options.verbose:
828                 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
829             matcher=re.compile("^(.*)%s(.*)"%oldname)
830             for line in tags.readlines():
831                 if not matcher.match(line):
832                     new.write(line)
833                 else:
834                     (begin,end)=matcher.match(line).groups()
835                     new.write(begin+newname+end+"\n")
836                     matches += 1
837         # brute-force : change uncommented lines that define <module>-SVNPATH
838         else:
839             if self.options.verbose:
840                 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
841             pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
842                                           %(self.name,self.name)
843             matcher_module=re.compile(pattern)
844             for line in tags.readlines():
845                 attempt=matcher_module.match(line)
846                 if attempt:
847                     if line.find("-GITPATH") >= 0:
848                         modulepath = "%s-GITPATH"%self.name
849                         replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
850                     else:
851                         modulepath = "%s-SVNPATH"%self.name
852                         replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
853                     if self.options.verbose:
854                         print ' ' + modulepath, 
855                     new.write(replacement)
856                     matches += 1
857                 else:
858                     new.write(line)
859         tags.close()
860         new.close()
861         os.rename(newtagsfile,tagsfile)
862         if self.options.verbose: print "%d changes"%matches
863         return matches
864
865     def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
866         if self.options.verbose:
867             print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
868
869         found_tagname = tagname
870         found = self.repository.tag_exists(tagname)
871         if not found and old_svn_tag_name:
872             if self.options.verbose:
873                 print "KO"
874                 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
875             found = self.repository.tag_exists(old_svn_tag_name)
876             if found:
877                 found_tagname = old_svn_tag_name
878
879         if (found and need_it) or (not found and not need_it):
880             if self.options.verbose:
881                 print "OK",
882                 if found: print "- found"
883                 else: print "- not found"
884         else:
885             if self.options.verbose:
886                 print "KO"
887             if found:
888                 raise Exception, "tag (%s) is already there" % tagname
889             else:
890                 raise Exception, "can not find required tag (%s)" % tagname
891
892         return found_tagname
893
894
895 ##############################
896     def do_tag (self):
897         self.init_module_dir()
898         self.revert_module_dir()
899         self.update_module_dir()
900         # parse specfile
901         spec_dict = self.spec_dict()
902         self.show_dict(spec_dict)
903         
904         # side effects
905         old_tag_name = self.tag_name(spec_dict)
906         old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
907
908         if (self.options.new_version):
909             # new version set on command line
910             spec_dict[self.module_version_varname] = self.options.new_version
911             spec_dict[self.module_taglevel_varname] = 0
912         else:
913             # increment taglevel
914             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
915             spec_dict[self.module_taglevel_varname] = new_taglevel
916
917         new_tag_name = self.tag_name(spec_dict)
918
919         # sanity check
920         old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
921         new_tag_name = self.check_tag(new_tag_name, need_it=False)
922
923         # checking for diffs
924         diff_output = self.repository.diff_with_tag(old_tag_name)
925         if len(diff_output) == 0:
926             if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
927                 return
928
929         # side effect in trunk's specfile
930         self.patch_spec_var(spec_dict)
931
932         # prepare changelog file 
933         # we use the standard subversion magic string (see svn_magic_line)
934         # so we can provide useful information, such as version numbers and diff
935         # in the same file
936         changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
937         changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
938         setting_tag_line=Module.setting_tag_format%new_tag_name
939         file(changelog,"w").write("""
940 %s
941 %s
942 Please write a changelog for this new tag in the section above
943 """%(Module.svn_magic_line,setting_tag_line))
944
945         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
946             file(changelog,"a").write('DIFF=========\n' + diff_output)
947         
948         if self.options.debug:
949             prompt('Proceed ?')
950
951         # edit it        
952         self.run("%s %s"%(self.options.editor,changelog))
953         # strip magic line in second file - looks like svn has changed its magic line with 1.6
954         # so we do the job ourselves
955         self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
956         # insert changelog in spec
957         if self.options.changelog:
958             self.insert_changelog (changelog,old_tag_name,new_tag_name)
959
960         ## update build
961         build_path = os.path.join(self.options.workdir,
962                                   Module.config['build'])
963         build = Repository(build_path, self.options)
964         if self.options.build_branch:
965             build.to_branch(self.options.build_branch)
966         if not build.is_clean():
967             build.revert()
968
969         tagsfiles=glob(build.path+"/*-tags*.mk")
970         tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
971         default_answer = 'y'
972         tagsfiles.sort()
973         while True:
974             for tagsfile in tagsfiles:
975                 status=tagsdict[tagsfile]
976                 basename=os.path.basename(tagsfile)
977                 print ".................... Dealing with %s"%basename
978                 while tagsdict[tagsfile] == 'todo' :
979                     choice = prompt ("insert %s in %s    "%(new_tag_name,basename),default_answer,
980                                      [ ('y','es'), ('n', 'ext'), ('f','orce'), 
981                                        ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
982                                      allow_outside=True)
983                     if choice == 'y':
984                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
985                     elif choice == 'n':
986                         print 'Done with %s'%os.path.basename(tagsfile)
987                         tagsdict[tagsfile]='done'
988                     elif choice == 'f':
989                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
990                     elif choice == 'd':
991                         print build.diff(f=os.path.basename(tagsfile))
992                     elif choice == 'r':
993                         build.revert(f=tagsfile)
994                     elif choice == 'c':
995                         self.run("cat %s"%tagsfile)
996                     else:
997                         name=self.name
998                         print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
999 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1000 d: show current diff for this tag file
1001 r: revert that tag file
1002 c: cat the current tag file
1003 n: move to next file"""%locals()
1004
1005             if prompt("Want to review changes on tags files",False):
1006                 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1007                 default_answer='d'
1008             else:
1009                 break
1010
1011         def diff_all_changes():
1012             print build.diff()
1013             print self.repository.diff()
1014
1015         def commit_all_changes(log):
1016             if hasattr(self,'branch'):
1017                 self.repository.commit(log, branch=self.branch)
1018             else:
1019                 self.repository.commit(log)
1020             build.commit(log)
1021
1022         self.run_prompt("Review module and build", diff_all_changes)
1023         self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1024         self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1025
1026         if self.options.debug:
1027             print 'Preserving',changelog,'and stripped',changelog_svn
1028         else:
1029             os.unlink(changelog)
1030             os.unlink(changelog_svn)
1031
1032
1033 ##############################
1034     def do_version (self):
1035         self.init_module_dir()
1036         self.revert_module_dir()
1037         self.update_module_dir()
1038         spec_dict = self.spec_dict()
1039         if self.options.www:
1040             self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1041                                                                   self.last_tag(spec_dict)))
1042         for varname in self.varnames:
1043             if not spec_dict.has_key(varname):
1044                 self.html_print ('Could not find %%define for %s'%varname)
1045                 return
1046             else:
1047                 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1048         self.html_print ("%-16s %s"%('url',self.repository.url()))
1049         if self.options.verbose:
1050             self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1051             self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1052         self.html_print_end()
1053
1054
1055 ##############################
1056     def do_diff (self):
1057         self.init_module_dir()
1058         self.revert_module_dir()
1059         self.update_module_dir()
1060         spec_dict = self.spec_dict()
1061         self.show_dict(spec_dict)
1062
1063         # side effects
1064         tag_name = self.tag_name(spec_dict)
1065         old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1066
1067         # sanity check
1068         tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1069
1070         if self.options.verbose:
1071             print 'Getting diff'
1072         diff_output = self.repository.diff_with_tag(tag_name)
1073
1074         if self.options.list:
1075             if diff_output:
1076                 print self.name
1077         else:
1078             thename=self.friendly_name()
1079             do_print=False
1080             if self.options.www and diff_output:
1081                 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1082                         thename,self.last_tag(spec_dict),len(diff_output)))
1083
1084                 self.html_store_raw ('<p> &lt; (left) %s </p>' % tag_name)
1085                 self.html_store_raw ('<p> &gt; (right) %s </p>' % thename)
1086                 self.html_store_pre (diff_output)
1087             elif not self.options.www:
1088                 print 'x'*30,'module',thename
1089                 print 'x'*20,'<',tag_name
1090                 print 'x'*20,'>',thename
1091                 print diff_output
1092
1093 ##############################
1094     # store and restitute html fragments
1095     @staticmethod 
1096     def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1097
1098     @staticmethod 
1099     def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1100
1101     @staticmethod
1102     def html_quote (text):
1103         return text.replace('&','&#38;').replace('<','&lt;').replace('>','&gt;')
1104
1105     # only the fake error module has multiple titles
1106     def html_store_title (self, title):
1107         if not hasattr(self,'titles'): self.titles=[]
1108         self.titles.append(title)
1109
1110     def html_store_raw (self, html):
1111         if not hasattr(self,'body'): self.body=''
1112         self.body += html
1113
1114     def html_store_pre (self, text):
1115         if not hasattr(self,'body'): self.body=''
1116         self.body += '<pre>' + self.html_quote(text) + '</pre>'
1117
1118     def html_print (self, txt):
1119         if not self.options.www:
1120             print txt
1121         else:
1122             if not hasattr(self,'in_list') or not self.in_list:
1123                 self.html_store_raw('<ul>')
1124                 self.in_list=True
1125             self.html_store_raw('<li>'+txt+'</li>')
1126
1127     def html_print_end (self):
1128         if self.options.www:
1129             self.html_store_raw ('</ul>')
1130
1131     @staticmethod
1132     def html_dump_header(title):
1133         nowdate=time.strftime("%Y-%m-%d")
1134         nowtime=time.strftime("%H:%M (%Z)")
1135         print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1136 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1137 <head>
1138 <title> %s </title>
1139 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1140 <style type="text/css">
1141 body { font-family:georgia, serif; }
1142 h1 {font-size: large; }
1143 p.title {font-size: x-large; }
1144 span.error {text-weight:bold; color: red; }
1145 </style>
1146 </head>
1147 <body>
1148 <p class='title'> %s - status on %s at %s</p>
1149 <ul>
1150 """%(title,title,nowdate,nowtime)
1151
1152     @staticmethod
1153     def html_dump_middle():
1154         print "</ul>"
1155
1156     @staticmethod
1157     def html_dump_footer():
1158         print "</body></html"
1159
1160     def html_dump_toc(self):
1161         if hasattr(self,'titles'):
1162             for title in self.titles:
1163                 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1164
1165     def html_dump_body(self):
1166         if hasattr(self,'titles'):
1167             for title in self.titles:
1168                 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1169         if hasattr(self,'body'):
1170             print self.body
1171             print '<p class="top">',self.html_href('#','Back to top'),'</p>'            
1172
1173
1174 ##############################
1175 class Main:
1176
1177     module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1178
1179 module-tools : a set of tools to manage subversion tags and specfile
1180   requires the specfile to either
1181   * define *version* and *taglevel*
1182   OR alternatively 
1183   * define redirection variables module_version_varname / module_taglevel_varname
1184 Trunk:
1185   by default, the trunk of modules is taken into account
1186   in this case, just mention the module name as <module_desc>
1187 Branches:
1188   if you wish to work on a branch rather than on the trunk, 
1189   you can use something like e.g. Mom:2.1 as <module_desc>
1190 """
1191     release_usage="""Usage: %prog [options] tag1 .. tagn
1192   Extract release notes from the changes in specfiles between several build tags, latest first
1193   Examples:
1194       release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1195   You can refer to a (build) branch by prepending a colon, like in
1196       release-changelog :4.2 4.2-rc25
1197   You can refer to the build trunk by just mentioning 'trunk', e.g.
1198       release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1199 """
1200     common_usage="""More help:
1201   see http://svn.planet-lab.org/wiki/ModuleTools"""
1202
1203     modes={ 
1204         'list' : "displays a list of available tags or branches",
1205         'version' : "check latest specfile and print out details",
1206         'diff' : "show difference between module (trunk or branch) and latest tag",
1207         'tag'  : """increment taglevel in specfile, insert changelog in specfile,
1208                 create new tag and and monitor its adoption in build/*-tags*.mk""",
1209         'branch' : """create a branch for this module, from the latest tag on the trunk, 
1210                   and change trunk's version number to reflect the new branch name;
1211                   you can specify the new branch name by using module:branch""",
1212         'sync' : """create a tag from the module
1213                 this is a last resort option, mostly for repairs""",
1214         'changelog' : """extract changelog between build tags
1215                 expected arguments are a list of tags""",
1216         }
1217
1218     silent_modes = ['list']
1219     release_modes = ['changelog']
1220
1221     @staticmethod
1222     def optparse_list (option, opt, value, parser):
1223         try:
1224             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1225         except:
1226             setattr(parser.values,option.dest,value.split())
1227
1228     def run(self):
1229
1230         mode=None
1231         for function in Main.modes.keys():
1232             if sys.argv[0].find(function) >= 0:
1233                 mode = function
1234                 break
1235         if not mode:
1236             print "Unsupported command",sys.argv[0]
1237             print "Supported commands:" + " ".join(Main.modes.keys())
1238             sys.exit(1)
1239
1240         if mode not in Main.release_modes:
1241             usage = Main.module_usage
1242             usage += Main.common_usage
1243             usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1244         else:
1245             usage = Main.release_usage
1246             usage += Main.common_usage
1247
1248         parser=OptionParser(usage=usage)
1249         
1250         if mode == "tag" or mode == 'branch':
1251             parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1252                               help="set new version and reset taglevel to 0")
1253         if mode == "tag" :
1254             parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1255                               help="do not update changelog section in specfile when tagging")
1256             parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1257                               help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1258         if mode == "tag" or mode == "sync" :
1259             parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1260                               help="specify editor")
1261
1262         if mode in ["diff","version"] :
1263             parser.add_option("-W","--www", action="store", dest="www", default=False,
1264                               help="export diff in html format, e.g. -W trunk")
1265
1266         if mode == "diff" :
1267             parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1268                               help="just list modules that exhibit differences")
1269             
1270         default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1271         parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1272                           help="run on all modules as found in %s"%default_modules_list)
1273         parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1274                           help="run on all modules found in specified file")
1275         parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1276                           help="dry run - shell commands are only displayed")
1277         parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1278                           default=[], nargs=1,type="string",
1279                           help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1280 -- can be set multiple times, or use quotes""")
1281
1282         parser.add_option("-w","--workdir", action="store", dest="workdir", 
1283                           default="%s/%s"%(os.getenv("HOME"),"modules"),
1284                           help="""name for dedicated working dir - defaults to ~/modules
1285 ** THIS MUST NOT ** be your usual working directory""")
1286         parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1287                           help="skip safety checks, such as svn updates -- use with care")
1288
1289         # default verbosity depending on function - temp
1290         verbose_modes= ['tag', 'sync', 'branch']
1291         
1292         if mode not in verbose_modes:
1293             parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
1294                               help="run in verbose mode")
1295         else:
1296             parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1297                               help="run in quiet (non-verbose) mode")
1298         (options, args) = parser.parse_args()
1299         options.mode=mode
1300         if not hasattr(options,'dry_run'):
1301             options.dry_run=False
1302         if not hasattr(options,'www'):
1303             options.www=False
1304         options.debug=False
1305
1306         ########## module-*
1307         if len(args) == 0:
1308             if options.all_modules:
1309                 options.modules_list=default_modules_list
1310             if options.modules_list:
1311                 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1312             else:
1313                 parser.print_help()
1314                 sys.exit(1)
1315         Module.init_homedir(options)
1316         
1317
1318         modules=[ Module(modname,options) for modname in args ]
1319         # hack: create a dummy Module to store errors/warnings
1320         error_module = Module('__errors__',options)
1321
1322         for module in modules:
1323             if len(args)>1 and mode not in Main.silent_modes:
1324                 if not options.www:
1325                     print '========================================',module.friendly_name()
1326             # call the method called do_<mode>
1327             method=Module.__dict__["do_%s"%mode]
1328             try:
1329                 method(module)
1330             except Exception,e:
1331                 if options.www:
1332                     title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1333                         (module.friendly_name(), str(e))
1334                     error_module.html_store_title(title)
1335                 else:
1336                     import traceback
1337                     traceback.print_exc()
1338                     print 'Skipping module %s: '%modname,e
1339
1340         if options.www:
1341             if mode == "diff":
1342                 modetitle="Changes to tag in %s"%options.www
1343             elif mode == "version":
1344                 modetitle="Latest tags in %s"%options.www
1345             modules.append(error_module)
1346             error_module.html_dump_header(modetitle)
1347             for module in modules:
1348                 module.html_dump_toc()
1349             Module.html_dump_middle()
1350             for module in modules:
1351                 module.html_dump_body()
1352             Module.html_dump_footer()
1353
1354 ####################
1355 if __name__ == "__main__" :
1356     try:
1357         Main().run()
1358     except KeyboardInterrupt:
1359         print '\nBye'