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