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