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