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