8749c4bcbbcc128dd9974ff3ee1f2f3bdedfcbe5
[moonshot.git] / rpm-builder
1 #!/usr/bin/python
2
3 '''A script to buildMoonshot  potentially using a schroot for install testing.
4 '''
5
6 from contextlib import contextmanager
7 import os, subprocess, exceptions
8 import re
9 import sys
10 from optparse import OptionParser
11 from shutil import copy
12
13
14
15 # These variables can be overridden by options. If packages is not
16 # set, then it is read from the rpm_packages file
17 packages = []  # Set of packages to build
18
19 class CommandError(exceptions.StandardError):
20     pass
21
22 def is_tarball(name):
23     return re.match('^.*\\.tar\\.gz', name)
24
25 def trim_tarball(t):
26     match = re.match('([^/-]*/)?([^-/]+)', t)
27     return match.group(2)
28
29 @contextmanager
30 def current_directory(dir):
31     "Change the current directory as a context manager; when the context exits, return."
32     cwd = os.getcwd()
33     os.chdir(dir)
34     yield
35     os.chdir(cwd)
36
37
38 def run_cmd(args, **kwords):
39     rcode =  subprocess.call( args, **kwords)
40     if rcode <> 0:
41         raise CommandError(args)
42
43 def command_output(args) :
44     p = subprocess.Popen(args, stdout=subprocess.PIPE)
45     output = p.communicate()
46     output = output[0]
47     if p.returncode != 0:
48         raise CommandError(args)
49     return output.strip()
50
51 def build(package):
52     run_cmd(['rpmbuild', '-ta', package])
53
54
55
56 def read_packages():
57     '''Read in the packages file from rpm_packages
58     '''
59     try: pf = file("rpm_packages")
60     except IOError:
61         print "Error: rpm_packages file not found"
62         exit(1)
63     def is_comment(line):
64         if re.match("^\\s*#", line): return False
65         if "#" in line: raise ValueError(
66             "Source package line contains a comment but not at beginning")
67         return True
68     return map(lambda(x): x.rstrip(),
69         filter(is_comment, pf.readlines()))
70
71
72 # main program
73 opt = OptionParser()
74 opt.usage = "%prog [options] distributions_dir [packages]"
75 (options, args) = opt.parse_args()
76 if len(args) == 0:
77     print "Distributions directory required"
78     exit(1)
79 dist_dir = args[0]
80 packages = args[1:]
81
82 if len(packages) == 0: packages = read_packages()
83 package_order = {}
84 count = 0
85 tarballs = filter(is_tarball, os.listdir(dist_dir))
86 for t in packages:
87     package_order[trim_tarball(t)] = count
88     count += 1
89     
90
91 os.umask(022)
92
93 try:
94     with current_directory(dist_dir):
95         tarballs.sort (key = lambda x: package_order[trim_tarball(x)])
96         for t in tarballs:
97             build(t)
98 except CommandError as c:
99     print "Error:" + str(c.args)
100     exit(1)
101
102
103     
104