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