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