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