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