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