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