initial commit for release-changelog
[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     # for parsing module spec name:branch
441     matcher_branch_spec=re.compile("\A(?P<name>[\w\.-]+):(?P<branch>[\w\.-]+)\Z")
442     # special form for tagged module - for Build
443     matcher_tag_spec=re.compile("\A(?P<name>[\w-]+)@(?P<tagname>[\w\.-]+)\Z")
444     # parsing specfiles
445     matcher_rpm_define=re.compile("%(define|global)\s+(\S+)\s+(\S*)\s*")
446
447     @classmethod
448     def parse_module_spec(cls, module_spec):
449         name = branch_or_tagname = module_type = ""
450
451         attempt=Module.matcher_branch_spec.match(module_spec)
452         if attempt:
453             module_type = "branch"
454             name=attempt.group('name')
455             branch_or_tagname=attempt.group('branch')
456         else:
457             attempt=Module.matcher_tag_spec.match(module_spec)
458             if attempt:
459                 module_type = "tag"
460                 name=attempt.group('name')
461                 branch_or_tagname=attempt.group('tagname')
462             else:
463                 name=module_spec
464         return name, branch_or_tagname, module_type
465
466
467     def __init__ (self,module_spec,options):
468         # parse module spec
469         self.name, branch_or_tagname, module_type = self.parse_module_spec(module_spec)
470
471         if module_type == "branch":
472             self.branch=branch_or_tagname
473         elif module_type == "tag":
474             self.tagname=branch_or_tagname
475
476         # when available prefer to use git module name internally
477         self.name = svn_to_git_name(self.name)
478
479         self.options=options
480         self.module_dir="%s/%s"%(options.workdir,self.name)
481         self.repository = None
482         self.build = None
483
484     def run (self,command):
485         return Command(command,self.options).run()
486     def run_fatal (self,command):
487         return Command(command,self.options).run_fatal()
488     def run_prompt (self,message,fun, *args):
489         fun_msg = "%s(%s)" % (fun.func_name, ",".join(args))
490         if not self.options.verbose:
491             while True:
492                 choice=prompt(message,True,('s','how'))
493                 if choice is True:
494                     fun(*args)
495                     return
496                 elif choice is False:
497                     print 'About to run function:', fun_msg
498         else:
499             question=message+" - want to run function: " + fun_msg
500             if prompt(question,True):
501                 fun(*args)
502
503     def friendly_name (self):
504         if hasattr(self,'branch'):
505             return "%s:%s"%(self.name,self.branch)
506         elif hasattr(self,'tagname'):
507             return "%s@%s"%(self.name,self.tagname)
508         else:
509             return self.name
510
511     @classmethod
512     def git_remote_dir (cls, name):
513         return "%s@%s:/git/%s.git" % (cls.config['gituser'], cls.config['gitserver'], name)
514
515     @classmethod
516     def svn_remote_dir (cls, name):
517         name = git_to_svn_name(name)
518         svn = cls.config['svnpath']
519         if svn.endswith('/'):
520             return "%s%s" % (svn, name)
521         return "%s/%s" % (svn, name)
522
523     def svn_selected_remote(self):
524         svn_name = git_to_svn_name(self.name)
525         remote = self.svn_remote_dir(svn_name)
526         if hasattr(self,'branch'):
527             remote = "%s/branches/%s" % (remote, self.branch)
528         elif hasattr(self,'tagname'):
529             remote = "%s/tags/%s" % (remote, self.tagname)
530         else:
531             remote = "%s/trunk" % remote
532         return remote
533
534     ####################
535     @classmethod
536     def init_homedir (cls, options):
537         if options.verbose and options.mode not in Main.silent_modes:
538             print 'Checking for', options.workdir
539         storage="%s/%s"%(options.workdir, cls.config_storage)
540         # sanity check. Either the topdir exists AND we have a config/storage
541         # or topdir does not exist and we create it
542         # to avoid people use their own daily svn repo
543         if os.path.isdir(options.workdir) and not os.path.isfile(storage):
544             print """The directory %s exists and has no CONFIG file
545 If this is your regular working directory, please provide another one as the
546 module-* commands need a fresh working dir. Make sure that you do not use 
547 that for other purposes than tagging""" % options.workdir
548             sys.exit(1)
549
550         def checkout_build():
551             print "Checking out build module..."
552             remote = cls.git_remote_dir(cls.config['build'])
553             local = os.path.join(options.workdir, cls.config['build'])
554             GitRepository.checkout(remote, local, options, depth=1)
555             print "OK"
556
557         def store_config():
558             f=file(storage,"w")
559             for (key,message,default) in Module.configKeys:
560                 f.write("%s=%s\n"%(key,Module.config[key]))
561             f.close()
562             if options.debug:
563                 print 'Stored',storage
564                 Command("cat %s"%storage,options).run()
565
566         def read_config():
567             # read config
568             f=open(storage)
569             for line in f.readlines():
570                 (key,value)=re.compile("^(.+)=(.+)$").match(line).groups()
571                 Module.config[key]=value                
572             f.close()
573
574         if not os.path.isdir (options.workdir):
575             print "Cannot find",options.workdir,"let's create it"
576             Command("mkdir -p %s" % options.workdir, options).run_silent()
577             cls.prompt_config()
578             checkout_build()
579             store_config()
580         else:
581             read_config()
582             # check missing config options
583             old_layout = False
584             for (key,message,default) in cls.configKeys:
585                 if not Module.config.has_key(key):
586                     print "Configuration changed for module-tools"
587                     cls.prompt_config_option(key, message, default)
588                     old_layout = True
589                     
590             if old_layout:
591                 Command("rm -rf %s" % options.workdir, options).run_silent()
592                 Command("mkdir -p %s" % options.workdir, options).run_silent()
593                 checkout_build()
594                 store_config()
595
596             build_dir = os.path.join(options.workdir, cls.config['build'])
597             if not os.path.isdir(build_dir):
598                 checkout_build()
599             else:
600                 build = Repository(build_dir, options)
601                 if not build.is_clean():
602                     print "build module needs a revert"
603                     build.revert()
604                     print "OK"
605                 build.update()
606
607         if options.verbose and options.mode not in Main.silent_modes:
608             print '******** Using config'
609             for (key,message,default) in Module.configKeys:
610                 print '\t',key,'=',Module.config[key]
611
612     def init_module_dir (self):
613         if self.options.verbose:
614             print 'Checking for',self.module_dir
615
616         if not os.path.isdir (self.module_dir):
617             if Repository.has_moved_to_git(self.name, Module.config):
618                 self.repository = GitRepository.checkout(self.git_remote_dir(self.name),
619                                                          self.module_dir,
620                                                          self.options)
621             else:
622                 remote = self.svn_selected_remote()
623                 self.repository = SvnRepository.checkout(remote,
624                                                          self.module_dir,
625                                                          self.options, recursive=False)
626
627         self.repository = Repository(self.module_dir, self.options)
628         if self.repository.type == "svn":
629             # check if module has moved to git    
630             if Repository.has_moved_to_git(self.name, Module.config):
631                 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
632                 self.init_module_dir()
633             # check if we have the required branch/tag
634             if self.repository.url() != self.svn_selected_remote():
635                 Command("rm -rf %s" % self.module_dir, self.options).run_silent()
636                 self.init_module_dir()
637
638         elif self.repository.type == "git":
639             if hasattr(self,'branch'):
640                 print "to branch", self.branch
641                 self.repository.to_branch(self.branch)
642             elif hasattr(self,'tagname'):
643                 print "to tag", self.tagname
644                 self.repository.to_tag(self.tagname)
645
646         else:
647             raise Exception, 'Cannot find %s - check module name'%self.module_dir
648
649
650     def revert_module_dir (self):
651         if self.options.fast_checks:
652             if self.options.verbose: print 'Skipping revert of %s' % self.module_dir
653             return
654         if self.options.verbose:
655             print 'Checking whether', self.module_dir, 'needs being reverted'
656         
657         if not self.repository.is_clean():
658             self.repository.revert()
659
660     def update_module_dir (self):
661         if self.options.fast_checks:
662             if self.options.verbose: print 'Skipping update of %s' % self.module_dir
663             return
664         if self.options.verbose:
665             print 'Updating', self.module_dir
666
667         if hasattr(self,'branch'):
668             self.repository.update(branch=self.branch)
669         elif hasattr(self,'tagname'):
670             self.repository.update(branch=self.tagname)
671         else:
672             self.repository.update()
673
674     def main_specname (self):
675         attempt="%s/%s.spec"%(self.module_dir,self.name)
676         if os.path.isfile (attempt):
677             return attempt
678         pattern1="%s/*.spec"%self.module_dir
679         level1=glob(pattern1)
680         if level1:
681             return level1[0]
682         pattern2="%s/*/*.spec"%self.module_dir
683         level2=glob(pattern2)
684
685         if level2:
686             return level2[0]
687         raise Exception, 'Cannot guess specfile for module %s -- patterns were %s or %s'%(self.name,pattern1,pattern2)
688
689     def all_specnames (self):
690         level1=glob("%s/*.spec" % self.module_dir)
691         if level1: return level1
692         level2=glob("%s/*/*.spec" % self.module_dir)
693         return level2
694
695     def parse_spec (self, specfile, varnames):
696         if self.options.verbose:
697             print 'Parsing',specfile,
698             for var in varnames:
699                 print "[%s]"%var,
700             print ""
701         result={}
702         f=open(specfile)
703         for line in f.readlines():
704             attempt=Module.matcher_rpm_define.match(line)
705             if attempt:
706                 (define,var,value)=attempt.groups()
707                 if var in varnames:
708                     result[var]=value
709         f.close()
710         if self.options.debug:
711             print 'found',len(result),'keys'
712             for (k,v) in result.iteritems():
713                 print k,'=',v
714         return result
715                 
716     # stores in self.module_name_varname the rpm variable to be used for the module's name
717     # and the list of these names in self.varnames
718     def spec_dict (self):
719         specfile=self.main_specname()
720         redirector_keys = [ varname for (varname,default) in Module.redirectors]
721         redirect_dict = self.parse_spec(specfile,redirector_keys)
722         if self.options.debug:
723             print '1st pass parsing done, redirect_dict=',redirect_dict
724         varnames=[]
725         for (varname,default) in Module.redirectors:
726             if redirect_dict.has_key(varname):
727                 setattr(self,varname,redirect_dict[varname])
728                 varnames += [redirect_dict[varname]]
729             else:
730                 setattr(self,varname,default)
731                 varnames += [ default ] 
732         self.varnames = varnames
733         result = self.parse_spec (specfile,self.varnames)
734         if self.options.debug:
735             print '2st pass parsing done, varnames=',varnames,'result=',result
736         return result
737
738     def patch_spec_var (self, patch_dict,define_missing=False):
739         for specfile in self.all_specnames():
740             # record the keys that were changed
741             changed = dict ( [ (x,False) for x in patch_dict.keys() ] )
742             newspecfile=specfile+".new"
743             if self.options.verbose:
744                 print 'Patching',specfile,'for',patch_dict.keys()
745             spec=open (specfile)
746             new=open(newspecfile,"w")
747
748             for line in spec.readlines():
749                 attempt=Module.matcher_rpm_define.match(line)
750                 if attempt:
751                     (define,var,value)=attempt.groups()
752                     if var in patch_dict.keys():
753                         if self.options.debug:
754                             print 'rewriting %s as %s'%(var,patch_dict[var])
755                         new.write('%%%s %s %s\n'%(define,var,patch_dict[var]))
756                         changed[var]=True
757                         continue
758                 new.write(line)
759             if define_missing:
760                 for (key,was_changed) in changed.iteritems():
761                     if not was_changed:
762                         if self.options.debug:
763                             print 'rewriting missing %s as %s'%(key,patch_dict[key])
764                         new.write('\n%%define %s %s\n'%(key,patch_dict[key]))
765             spec.close()
766             new.close()
767             os.rename(newspecfile,specfile)
768
769     # returns all lines until the magic line
770     def unignored_lines (self, logfile):
771         result=[]
772         white_line_matcher = re.compile("\A\s*\Z")
773         for logline in file(logfile).readlines():
774             if logline.strip() == Module.svn_magic_line:
775                 break
776             elif white_line_matcher.match(logline):
777                 continue
778             else:
779                 result.append(logline.strip()+'\n')
780         return result
781
782     # creates a copy of the input with only the unignored lines
783     def stripped_magic_line_filename (self, filein, fileout ,new_tag_name):
784        f=file(fileout,'w')
785        f.write(self.setting_tag_format%new_tag_name + '\n')
786        for line in self.unignored_lines(filein):
787            f.write(line)
788        f.close()
789
790     def insert_changelog (self, logfile, oldtag, newtag):
791         for specfile in self.all_specnames():
792             newspecfile=specfile+".new"
793             if self.options.verbose:
794                 print 'Inserting changelog from %s into %s'%(logfile,specfile)
795             spec=open (specfile)
796             new=open(newspecfile,"w")
797             for line in spec.readlines():
798                 new.write(line)
799                 if re.compile('%changelog').match(line):
800                     dateformat="* %a %b %d %Y"
801                     datepart=time.strftime(dateformat)
802                     logpart="%s <%s> - %s"%(Module.config['username'],
803                                                  Module.config['email'],
804                                                  newtag)
805                     new.write(datepart+" "+logpart+"\n")
806                     for logline in self.unignored_lines(logfile):
807                         new.write("- " + logline)
808                     new.write("\n")
809             spec.close()
810             new.close()
811             os.rename(newspecfile,specfile)
812             
813     def show_dict (self, spec_dict):
814         if self.options.verbose:
815             for (k,v) in spec_dict.iteritems():
816                 print k,'=',v
817
818     def last_tag (self, spec_dict):
819         try:
820             return "%s-%s" % (spec_dict[self.module_version_varname],
821                               spec_dict[self.module_taglevel_varname])
822         except KeyError,err:
823             raise Exception,'Something is wrong with module %s, cannot determine %s - exiting'%(self.name,err)
824
825     def tag_name (self, spec_dict, old_svn_name=False):
826         base_tag_name = self.name
827         if old_svn_name:
828             base_tag_name = git_to_svn_name(self.name)
829         return "%s-%s" % (base_tag_name, self.last_tag(spec_dict))
830     
831
832 ##############################
833     # using fine_grain means replacing only those instances that currently refer to this tag
834     # otherwise, <module>-{SVNPATH,GITPATH} is replaced unconditionnally
835     def patch_tags_file (self, tagsfile, oldname, newname,fine_grain=True):
836         newtagsfile=tagsfile+".new"
837         tags=open (tagsfile)
838         new=open(newtagsfile,"w")
839
840         matches=0
841         # fine-grain : replace those lines that refer to oldname
842         if fine_grain:
843             if self.options.verbose:
844                 print 'Replacing %s into %s\n\tin %s .. '%(oldname,newname,tagsfile),
845             matcher=re.compile("^(.*)%s(.*)"%oldname)
846             for line in tags.readlines():
847                 if not matcher.match(line):
848                     new.write(line)
849                 else:
850                     (begin,end)=matcher.match(line).groups()
851                     new.write(begin+newname+end+"\n")
852                     matches += 1
853         # brute-force : change uncommented lines that define <module>-SVNPATH
854         else:
855             if self.options.verbose:
856                 print 'Searching for -SVNPATH or -GITPATH lines referring to /%s/\n\tin %s .. '%(self.name,tagsfile),
857             pattern="\A\s*%s-(SVNPATH|GITPATH)\s*(=|:=)\s*(?P<url_main>[^\s]+)/%s[^\s]+"\
858                                           %(self.name,self.name)
859             matcher_module=re.compile(pattern)
860             for line in tags.readlines():
861                 attempt=matcher_module.match(line)
862                 if attempt:
863                     if line.find("-GITPATH") >= 0:
864                         modulepath = "%s-GITPATH"%self.name
865                         replacement = "%-32s:= %s/%s.git@%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
866                     else:
867                         modulepath = "%s-SVNPATH"%self.name
868                         replacement = "%-32s:= %s/%s/tags/%s\n"%(modulepath,attempt.group('url_main'),self.name,newname)
869                     if self.options.verbose:
870                         print ' ' + modulepath, 
871                     new.write(replacement)
872                     matches += 1
873                 else:
874                     new.write(line)
875         tags.close()
876         new.close()
877         os.rename(newtagsfile,tagsfile)
878         if self.options.verbose: print "%d changes"%matches
879         return matches
880
881     def check_tag(self, tagname, need_it=False, old_svn_tag_name=None):
882         if self.options.verbose:
883             print "Checking %s repository tag: %s - " % (self.repository.type, tagname),
884
885         found_tagname = tagname
886         found = self.repository.tag_exists(tagname)
887         if not found and old_svn_tag_name:
888             if self.options.verbose:
889                 print "KO"
890                 print "Checking %s repository tag: %s - " % (self.repository.type, old_svn_tag_name),
891             found = self.repository.tag_exists(old_svn_tag_name)
892             if found:
893                 found_tagname = old_svn_tag_name
894
895         if (found and need_it) or (not found and not need_it):
896             if self.options.verbose:
897                 print "OK",
898                 if found: print "- found"
899                 else: print "- not found"
900         else:
901             if self.options.verbose:
902                 print "KO"
903             if found:
904                 raise Exception, "tag (%s) is already there" % tagname
905             else:
906                 raise Exception, "can not find required tag (%s)" % tagname
907
908         return found_tagname
909
910
911 ##############################
912     def do_tag (self):
913         self.init_module_dir()
914         self.revert_module_dir()
915         self.update_module_dir()
916         # parse specfile
917         spec_dict = self.spec_dict()
918         self.show_dict(spec_dict)
919         
920         # side effects
921         old_tag_name = self.tag_name(spec_dict)
922         old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
923
924         if (self.options.new_version):
925             # new version set on command line
926             spec_dict[self.module_version_varname] = self.options.new_version
927             spec_dict[self.module_taglevel_varname] = 0
928         else:
929             # increment taglevel
930             new_taglevel = str ( int (spec_dict[self.module_taglevel_varname]) + 1)
931             spec_dict[self.module_taglevel_varname] = new_taglevel
932
933         new_tag_name = self.tag_name(spec_dict)
934
935         # sanity check
936         old_tag_name = self.check_tag(old_tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
937         new_tag_name = self.check_tag(new_tag_name, need_it=False)
938
939         # checking for diffs
940         diff_output = self.repository.diff_with_tag(old_tag_name)
941         if len(diff_output) == 0:
942             if not prompt ("No pending difference in module %s, want to tag anyway"%self.name,False):
943                 return
944
945         # side effect in trunk's specfile
946         self.patch_spec_var(spec_dict)
947
948         # prepare changelog file 
949         # we use the standard subversion magic string (see svn_magic_line)
950         # so we can provide useful information, such as version numbers and diff
951         # in the same file
952         changelog="/tmp/%s-%d.edit"%(self.name,os.getpid())
953         changelog_svn="/tmp/%s-%d.svn"%(self.name,os.getpid())
954         setting_tag_line=Module.setting_tag_format%new_tag_name
955         file(changelog,"w").write("""
956 %s
957 %s
958 Please write a changelog for this new tag in the section above
959 """%(Module.svn_magic_line,setting_tag_line))
960
961         if not self.options.verbose or prompt('Want to see diffs while writing changelog',True):
962             file(changelog,"a").write('DIFF=========\n' + diff_output)
963         
964         if self.options.debug:
965             prompt('Proceed ?')
966
967         # edit it        
968         self.run("%s %s"%(self.options.editor,changelog))
969         # strip magic line in second file - looks like svn has changed its magic line with 1.6
970         # so we do the job ourselves
971         self.stripped_magic_line_filename(changelog,changelog_svn,new_tag_name)
972         # insert changelog in spec
973         if self.options.changelog:
974             self.insert_changelog (changelog,old_tag_name,new_tag_name)
975
976         ## update build
977         build_path = os.path.join(self.options.workdir,
978                                   Module.config['build'])
979         build = Repository(build_path, self.options)
980         if self.options.build_branch:
981             build.to_branch(self.options.build_branch)
982         if not build.is_clean():
983             build.revert()
984
985         tagsfiles=glob(build.path+"/*-tags*.mk")
986         tagsdict=dict( [ (x,'todo') for x in tagsfiles ] )
987         default_answer = 'y'
988         tagsfiles.sort()
989         while True:
990             for tagsfile in tagsfiles:
991                 status=tagsdict[tagsfile]
992                 basename=os.path.basename(tagsfile)
993                 print ".................... Dealing with %s"%basename
994                 while tagsdict[tagsfile] == 'todo' :
995                     choice = prompt ("insert %s in %s    "%(new_tag_name,basename),default_answer,
996                                      [ ('y','es'), ('n', 'ext'), ('f','orce'), 
997                                        ('d','iff'), ('r','evert'), ('c', 'at'), ('h','elp') ] ,
998                                      allow_outside=True)
999                     if choice == 'y':
1000                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=True)
1001                     elif choice == 'n':
1002                         print 'Done with %s'%os.path.basename(tagsfile)
1003                         tagsdict[tagsfile]='done'
1004                     elif choice == 'f':
1005                         self.patch_tags_file(tagsfile,old_tag_name,new_tag_name,fine_grain=False)
1006                     elif choice == 'd':
1007                         print build.diff(f=os.path.basename(tagsfile))
1008                     elif choice == 'r':
1009                         build.revert(f=tagsfile)
1010                     elif choice == 'c':
1011                         self.run("cat %s"%tagsfile)
1012                     else:
1013                         name=self.name
1014                         print """y: change %(name)s-{SVNPATH,GITPATH} only if it currently refers to %(old_tag_name)s
1015 f: unconditionnally change any line that assigns %(name)s-SVNPATH to using %(new_tag_name)s
1016 d: show current diff for this tag file
1017 r: revert that tag file
1018 c: cat the current tag file
1019 n: move to next file"""%locals()
1020
1021             if prompt("Want to review changes on tags files",False):
1022                 tagsdict = dict ( [ (x, 'todo') for x in tagsfiles ] )
1023                 default_answer='d'
1024             else:
1025                 break
1026
1027         def diff_all_changes():
1028             print build.diff()
1029             print self.repository.diff()
1030
1031         def commit_all_changes(log):
1032             if hasattr(self,'branch'):
1033                 self.repository.commit(log, branch=self.branch)
1034             else:
1035                 self.repository.commit(log)
1036             build.commit(log)
1037
1038         self.run_prompt("Review module and build", diff_all_changes)
1039         self.run_prompt("Commit module and build", commit_all_changes, changelog_svn)
1040         self.run_prompt("Create tag", self.repository.tag, new_tag_name, changelog_svn)
1041
1042         if self.options.debug:
1043             print 'Preserving',changelog,'and stripped',changelog_svn
1044         else:
1045             os.unlink(changelog)
1046             os.unlink(changelog_svn)
1047
1048
1049 ##############################
1050     def do_version (self):
1051         self.init_module_dir()
1052         self.revert_module_dir()
1053         self.update_module_dir()
1054         spec_dict = self.spec_dict()
1055         if self.options.www:
1056             self.html_store_title('Version for module %s (%s)' % (self.friendly_name(),
1057                                                                   self.last_tag(spec_dict)))
1058         for varname in self.varnames:
1059             if not spec_dict.has_key(varname):
1060                 self.html_print ('Could not find %%define for %s'%varname)
1061                 return
1062             else:
1063                 self.html_print ("%-16s %s"%(varname,spec_dict[varname]))
1064         self.html_print ("%-16s %s"%('url',self.repository.url()))
1065         if self.options.verbose:
1066             self.html_print ("%-16s %s"%('main specfile:',self.main_specname()))
1067             self.html_print ("%-16s %s"%('specfiles:',self.all_specnames()))
1068         self.html_print_end()
1069
1070
1071 ##############################
1072     def do_diff (self):
1073         self.init_module_dir()
1074         self.revert_module_dir()
1075         self.update_module_dir()
1076         spec_dict = self.spec_dict()
1077         self.show_dict(spec_dict)
1078
1079         # side effects
1080         tag_name = self.tag_name(spec_dict)
1081         old_svn_tag_name = self.tag_name(spec_dict, old_svn_name=True)
1082
1083         # sanity check
1084         tag_name = self.check_tag(tag_name, need_it=True, old_svn_tag_name=old_svn_tag_name)
1085
1086         if self.options.verbose:
1087             print 'Getting diff'
1088         diff_output = self.repository.diff_with_tag(tag_name)
1089
1090         if self.options.list:
1091             if diff_output:
1092                 print self.name
1093         else:
1094             thename=self.friendly_name()
1095             do_print=False
1096             if self.options.www and diff_output:
1097                 self.html_store_title("Diffs in module %s (%s) : %d chars"%(\
1098                         thename,self.last_tag(spec_dict),len(diff_output)))
1099
1100                 self.html_store_raw ('<p> &lt; (left) %s </p>' % tag_name)
1101                 self.html_store_raw ('<p> &gt; (right) %s </p>' % thename)
1102                 self.html_store_pre (diff_output)
1103             elif not self.options.www:
1104                 print 'x'*30,'module',thename
1105                 print 'x'*20,'<',tag_name
1106                 print 'x'*20,'>',thename
1107                 print diff_output
1108
1109 ##############################
1110     # store and restitute html fragments
1111     @staticmethod 
1112     def html_href (url,text): return '<a href="%s">%s</a>'%(url,text)
1113
1114     @staticmethod 
1115     def html_anchor (url,text): return '<a name="%s">%s</a>'%(url,text)
1116
1117     @staticmethod
1118     def html_quote (text):
1119         return text.replace('&','&#38;').replace('<','&lt;').replace('>','&gt;')
1120
1121     # only the fake error module has multiple titles
1122     def html_store_title (self, title):
1123         if not hasattr(self,'titles'): self.titles=[]
1124         self.titles.append(title)
1125
1126     def html_store_raw (self, html):
1127         if not hasattr(self,'body'): self.body=''
1128         self.body += html
1129
1130     def html_store_pre (self, text):
1131         if not hasattr(self,'body'): self.body=''
1132         self.body += '<pre>' + self.html_quote(text) + '</pre>'
1133
1134     def html_print (self, txt):
1135         if not self.options.www:
1136             print txt
1137         else:
1138             if not hasattr(self,'in_list') or not self.in_list:
1139                 self.html_store_raw('<ul>')
1140                 self.in_list=True
1141             self.html_store_raw('<li>'+txt+'</li>')
1142
1143     def html_print_end (self):
1144         if self.options.www:
1145             self.html_store_raw ('</ul>')
1146
1147     @staticmethod
1148     def html_dump_header(title):
1149         nowdate=time.strftime("%Y-%m-%d")
1150         nowtime=time.strftime("%H:%M (%Z)")
1151         print """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1152 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
1153 <head>
1154 <title> %s </title>
1155 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1156 <style type="text/css">
1157 body { font-family:georgia, serif; }
1158 h1 {font-size: large; }
1159 p.title {font-size: x-large; }
1160 span.error {text-weight:bold; color: red; }
1161 </style>
1162 </head>
1163 <body>
1164 <p class='title'> %s - status on %s at %s</p>
1165 <ul>
1166 """%(title,title,nowdate,nowtime)
1167
1168     @staticmethod
1169     def html_dump_middle():
1170         print "</ul>"
1171
1172     @staticmethod
1173     def html_dump_footer():
1174         print "</body></html"
1175
1176     def html_dump_toc(self):
1177         if hasattr(self,'titles'):
1178             for title in self.titles:
1179                 print '<li>',self.html_href ('#'+self.friendly_name(),title),'</li>'
1180
1181     def html_dump_body(self):
1182         if hasattr(self,'titles'):
1183             for title in self.titles:
1184                 print '<hr /><h1>',self.html_anchor(self.friendly_name(),title),'</h1>'
1185         if hasattr(self,'body'):
1186             print self.body
1187             print '<p class="top">',self.html_href('#','Back to top'),'</p>'            
1188
1189
1190
1191 def release_changelog(options, buildtag1, buildtag2, tagfile):
1192     build = Module("build@%s" % buildtag1, options)
1193     build.init_module_dir()
1194     
1195 #     tagfile = os.path.join(build.module_dir, tagfile)
1196 #     for line in open(tagfile):
1197 #         try:
1198 #             url = line.split(':=')[1]
1199 #             print build.parse_module_spec(url)
1200 #         except:
1201 #             pass
1202
1203     os.system("cp %s/%s /tmp" % (build.module_dir, tagfile))
1204
1205     build = Module("build@%s" % buildtag2, options)
1206     build.init_module_dir()
1207     
1208     print os.system("diff -u /tmp/%s %s/%s" % (tagfile, build.module_dir, tagfile))
1209
1210
1211
1212
1213 ##############################
1214 class Main:
1215
1216     module_usage="""Usage: %prog [options] module_desc [ .. module_desc ]
1217
1218 module-tools : a set of tools to manage subversion tags and specfile
1219   requires the specfile to either
1220   * define *version* and *taglevel*
1221   OR alternatively 
1222   * define redirection variables module_version_varname / module_taglevel_varname
1223 Trunk:
1224   by default, the trunk of modules is taken into account
1225   in this case, just mention the module name as <module_desc>
1226 Branches:
1227   if you wish to work on a branch rather than on the trunk, 
1228   you can use something like e.g. Mom:2.1 as <module_desc>
1229 """
1230     release_usage="""Usage: %prog [options] tag1 .. tagn
1231   Extract release notes from the changes in specfiles between several build tags, latest first
1232   Examples:
1233       release-changelog 4.2-rc25 4.2-rc24 4.2-rc23 4.2-rc22
1234   You can refer to a (build) branch by prepending a colon, like in
1235       release-changelog :4.2 4.2-rc25
1236   You can refer to the build trunk by just mentioning 'trunk', e.g.
1237       release-changelog -t coblitz-tags.mk coblitz-2.01-rc6 trunk
1238 """
1239     common_usage="""More help:
1240   see http://svn.planet-lab.org/wiki/ModuleTools"""
1241
1242     modes={ 
1243         'list' : "displays a list of available tags or branches",
1244         'version' : "check latest specfile and print out details",
1245         'diff' : "show difference between module (trunk or branch) and latest tag",
1246         'tag'  : """increment taglevel in specfile, insert changelog in specfile,
1247                 create new tag and and monitor its adoption in build/*-tags*.mk""",
1248         'branch' : """create a branch for this module, from the latest tag on the trunk, 
1249                   and change trunk's version number to reflect the new branch name;
1250                   you can specify the new branch name by using module:branch""",
1251         'sync' : """create a tag from the module
1252                 this is a last resort option, mostly for repairs""",
1253         'changelog' : """extract changelog between build tags
1254                 expected arguments are a list of tags""",
1255         }
1256
1257     silent_modes = ['list']
1258     release_modes = ['changelog']
1259
1260     @staticmethod
1261     def optparse_list (option, opt, value, parser):
1262         try:
1263             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
1264         except:
1265             setattr(parser.values,option.dest,value.split())
1266
1267     def run(self):
1268
1269         mode=None
1270         for function in Main.modes.keys():
1271             if sys.argv[0].find(function) >= 0:
1272                 mode = function
1273                 break
1274         if not mode:
1275             print "Unsupported command",sys.argv[0]
1276             print "Supported commands:" + " ".join(Main.modes.keys())
1277             sys.exit(1)
1278
1279         if mode not in Main.release_modes:
1280             usage = Main.module_usage
1281             usage += Main.common_usage
1282             usage += "\nmodule-%s : %s"%(mode,Main.modes[mode])
1283         else:
1284             usage = Main.release_usage
1285             usage += Main.common_usage
1286
1287         parser=OptionParser(usage=usage)
1288         
1289         if mode == "tag" or mode == 'branch':
1290             parser.add_option("-s","--set-version",action="store",dest="new_version",default=None,
1291                               help="set new version and reset taglevel to 0")
1292         if mode == "tag" :
1293             parser.add_option("-c","--no-changelog", action="store_false", dest="changelog", default=True,
1294                               help="do not update changelog section in specfile when tagging")
1295             parser.add_option("-b","--build-branch", action="store", dest="build_branch", default=None,
1296                               help="specify a build branch; used for locating the *tags*.mk files where adoption is to take place")
1297         if mode == "tag" or mode == "sync" :
1298             parser.add_option("-e","--editor", action="store", dest="editor", default=default_editor(),
1299                               help="specify editor")
1300
1301         if mode in ["diff","version"] :
1302             parser.add_option("-W","--www", action="store", dest="www", default=False,
1303                               help="export diff in html format, e.g. -W trunk")
1304
1305         if mode == "diff" :
1306             parser.add_option("-l","--list", action="store_true", dest="list", default=False,
1307                               help="just list modules that exhibit differences")
1308             
1309         default_modules_list=os.path.dirname(sys.argv[0])+"/modules.list"
1310         parser.add_option("-a","--all",action="store_true",dest="all_modules",default=False,
1311                           help="run on all modules as found in %s"%default_modules_list)
1312         parser.add_option("-f","--file",action="store",dest="modules_list",default=None,
1313                           help="run on all modules found in specified file")
1314         parser.add_option("-n","--dry-run",action="store_true",dest="dry_run",default=False,
1315                           help="dry run - shell commands are only displayed")
1316         parser.add_option("-t","--distrotags",action="callback",callback=Main.optparse_list, dest="distrotags",
1317                           default=[], nargs=1,type="string",
1318                           help="""specify distro-tags files, e.g. onelab-tags-4.2.mk
1319 -- can be set multiple times, or use quotes""")
1320
1321         parser.add_option("-w","--workdir", action="store", dest="workdir", 
1322                           default="%s/%s"%(os.getenv("HOME"),"modules"),
1323                           help="""name for dedicated working dir - defaults to ~/modules
1324 ** THIS MUST NOT ** be your usual working directory""")
1325         parser.add_option("-F","--fast-checks",action="store_true",dest="fast_checks",default=False,
1326                           help="skip safety checks, such as svn updates -- use with care")
1327
1328         # default verbosity depending on function - temp
1329         verbose_modes= ['tag', 'sync', 'branch']
1330         
1331         if mode not in verbose_modes:
1332             parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
1333                               help="run in verbose mode")
1334         else:
1335             parser.add_option("-q","--quiet", action="store_false", dest="verbose", default=True,
1336                               help="run in quiet (non-verbose) mode")
1337         (options, args) = parser.parse_args()
1338         options.mode=mode
1339         if not hasattr(options,'dry_run'):
1340             options.dry_run=False
1341         if not hasattr(options,'www'):
1342             options.www=False
1343         options.debug=False
1344
1345         ########## module-*
1346         if len(args) == 0:
1347             if options.all_modules:
1348                 options.modules_list=default_modules_list
1349             if options.modules_list:
1350                 args=Command("grep -v '#' %s"%options.modules_list,options).output_of().split()
1351             else:
1352                 parser.print_help()
1353                 sys.exit(1)
1354         Module.init_homedir(options)
1355         
1356
1357         if mode not in Main.release_modes:
1358             modules=[ Module(modname,options) for modname in args ]
1359             # hack: create a dummy Module to store errors/warnings
1360             error_module = Module('__errors__',options)
1361
1362             for module in modules:
1363                 if len(args)>1 and mode not in Main.silent_modes:
1364                     if not options.www:
1365                         print '========================================',module.friendly_name()
1366                 # call the method called do_<mode>
1367                 method=Module.__dict__["do_%s"%mode]
1368                 try:
1369                     method(module)
1370                 except Exception,e:
1371                     if options.www:
1372                         title='<span class="error"> Skipping module %s - failure: %s </span>'%\
1373                             (module.friendly_name(), str(e))
1374                         error_module.html_store_title(title)
1375                     else:
1376                         import traceback
1377                         traceback.print_exc()
1378                         print 'Skipping module %s: '%modname,e
1379     
1380             if options.www:
1381                 if mode == "diff":
1382                     modetitle="Changes to tag in %s"%options.www
1383                 elif mode == "version":
1384                     modetitle="Latest tags in %s"%options.www
1385                 modules.append(error_module)
1386                 error_module.html_dump_header(modetitle)
1387                 for module in modules:
1388                     module.html_dump_toc()
1389                 Module.html_dump_middle()
1390                 for module in modules:
1391                     module.html_dump_body()
1392                 Module.html_dump_footer()
1393         else:
1394             release_changelog(options, *args)
1395             
1396     
1397 ####################
1398 if __name__ == "__main__" :
1399     try:
1400         Main().run()
1401     except KeyboardInterrupt:
1402         print '\nBye'