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