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