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