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