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