better error message in case of config file errors
[auto-debuild.git] / auto_debuild.py
1 #!/usr/bin/python
2 import os, shutil, stat, time, subprocess, sys
3 from collections import OrderedDict
4
5 # a dict with some useful additional getters
6 class AdvancedDict(dict):
7         def getstr(self, name, default = None):
8                 if not name in self: return default
9                 val = self[name]
10                 if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
11                 return val[0]
12         
13         def getint(self, name, default = None):
14                 return int(self.getstr(name, default))
15         
16         def getbool(self, name, default = None):
17                 val = self.getstr(name, default)
18                 if isinstance(val, bool): return val # already a bool
19                 return val.lower() in ('true', 'yes', 'on', '1')
20
21 # create a safe-to-call shell command from the array
22 def safeCall(*args):
23         res = ""
24         for arg in args:
25                 assert arg.find("'") < 0 # ' is not supported
26                 if len(res): res += " "
27                 res += "'"+arg+"'"
28         return res
29
30 # Load a section-less config file: maps parameter names to strings or lists of strings (which are comma-separated or in separate lines)
31 # Lines starting with spaces are continuation lines
32 def loadConfigFile(file):
33         import shlex
34         # read config file
35         linenr = 0
36         with open(file) as file:
37                 result = AdvancedDict()
38                 curKey = None
39                 for line in file:
40                         linenr += 1
41                         isCont = len(line) and line[0].isspace() # remember if we were a continuation line
42                         if isCont and curKey is None:
43                                 raise Exception("Invalid config, line %d: Starting with continuation line" % linenr)
44                         line = line.strip()
45                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
46                         try:
47                                 if isCont:
48                                         # continuation line
49                                         result[curKey] += shlex.split(line)
50                                 else:
51                                         # option line
52                                         pos = line.index("=") # will raise exception when substring is not found
53                                         curKey = line[:pos].strip()
54                                         value = line[pos+1:]
55                                         result[curKey] = shlex.split(value)
56                         except Exception:
57                                 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
58         # add some convencience get functions
59         return result
60
61 # representation of a build system
62 class BuildSystem:
63         def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
64                 self.ruleMaker = ruleMaker
65                 self.buildDepends = buildDepends
66                 self.binaryDepends = binaryDepends
67
68 # abstract representation of rules file
69 class RulesFile:
70         def __init__(self):
71                 self.env = {}
72                 self.dh = []
73                 self.dhWith = set()
74                 self.rules = OrderedDict()
75         
76         def env2str(self):
77                 res = ""
78                 for name in self.env: # we rely on the name being sane (i.e., no special characters)
79                         val = self.env[name]
80                         assert val.find("'") < 0 # ' is not supported
81                         if len(res): res += " "
82                         res += name+"='"+val+"'"
83                 return res
84
85         def write(self, f):
86                 print >>f, "#!/usr/bin/make -f"
87                 print >>f, ""
88                 print >>f, ".PHONY: build" # there may be a directory called "build"
89                 print >>f, ""
90                 print >>f, "build %:" # need to mention "build" here again explicitly so PHONY takes effect
91                 # write proper dh call
92                 dh = self.dh
93                 if self.dhWith:
94                         dh.append('--with='+','.join(self.dhWith))
95                 print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(*dh)
96                 # write remaining rules
97                 for rule in self.rules:
98                         print >>f, ""
99                         print >>f, "override_dh_"+rule+":"
100                         for line in self.rules[rule]:
101                                 print >>f, "\t"+line
102
103 # rule-makers
104 def cmakeRules(config):
105         buildDir = config.getstr('buildDir', 'build')
106         srcDir = os.getcwd()
107         r = RulesFile()
108         r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
109         r.rules['auto_configure'] = [
110                 safeCall("mkdir", "-p", buildDir),
111                 safeCall("cd", buildDir) + " && " +
112                   safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
113         ]
114         r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
115         return r
116
117 def automakeRules(config):
118         # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
119         # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
120         #  and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
121         r = RulesFile()
122         r.dh += ["--buildsystem=autoconf"]
123         r.rules['auto_configure'] = [
124                 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
125                 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
126                         './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
127                         '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
128                         '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
129                         '--sysconfdir=/etc --localstatedir=/var '+
130                         safeCall(*config.get('automakeParameters', []))
131         ]
132         r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
133         return r
134
135 def pythonRules(config):
136         r = RulesFile()
137         r.dh += ["--buildsystem=python_distutils"]
138         r.dhWith.add('python2')
139         r.rules['auto_clean'] = [ # clean properly
140                 'dh_auto_clean',
141                 'rm -rf build'
142         ]
143         return r
144
145 # build systems
146 buildSystems = {
147         'cmake': BuildSystem(cmakeRules, ["cmake"]),
148         'automake': BuildSystem(automakeRules),
149         'python': BuildSystem(pythonRules, ["python-setuptools"], ["${python:Depends}"]),
150 }
151
152 # utility functions
153 def commandInBuildEnv(config, command):
154         schroot = config.getstr('schroot')
155         if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
156         return command
157
158 def getArchitecture(config):
159         cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
160         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
161         res = p.communicate()[0] # get only stdout
162         if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
163         return res[0:len(res)-1] # chop of the \n at the end
164
165 def writeDependency(f, name, list):
166         if len(list):
167                 print >>f, name+": "+', '.join(list)
168
169 # actual work functions
170 def createDebianFiles(config):
171         sourceName = config.getstr('sourceName')
172         binaryName = config.getstr('binaryName', sourceName+'-local')
173         name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
174         email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
175         debDir = os.path.expanduser(config.getstr('debDir'))
176         buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
177         version = config.getstr('version')
178         dbgPackage = config.getbool('dbgPackage', False)
179         parallelJobs = config.getint('parallelJobs', 2)
180         packageArchitecture = config.getstr('architecture', 'any')
181         withPython2 = config.getbool('withPython2', False)
182         if withPython2:
183                 buildSystem.binaryDepends.append("${python:Depends}") # HACK, but it works: make sure dependencies on binary are added
184         # we return the list of files generated, so we need to know the architecture
185         arch = getArchitecture(config)
186         files = []
187         # create folders
188         if os.path.exists('debian'): raise Exception('debian folder already exists?')
189         os.mkdir('debian')
190         os.mkdir('debian/source')
191         if not os.path.exists(debDir): os.makedirs(debDir)
192         # source format file
193         with open('debian/source/format', 'w') as f:
194                 print >>f, "3.0 (native)"
195         # compat file
196         with open('debian/compat', 'w') as f:
197                 print >>f, "9"
198         # copyright file
199         with open('debian/copyright', 'w') as f:
200                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
201         # changelog file
202         with open('debian/changelog', 'w') as f:
203                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
204                 print >>f, ""
205                 print >>f, "  * Auto-generated by auto-debuild"
206                 print >>f, ""
207                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
208         # control file
209         with open('debian/control', 'w') as f:
210                 print >>f, "Source:",sourceName
211                 print >>f, "Section:",config.getstr('section', 'misc')
212                 print >>f, "Priority: extra"
213                 print >>f, "Maintainer: %s <%s>" % (name, email)
214                 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
215                 print >>f, "Standards-Version: 3.9.3"
216                 print >>f, ""
217                 print >>f, "Package:",binaryName
218                 print >>f, "Architecture:",packageArchitecture
219                 if 'binaryMultiArch' in config:
220                         print >>f, "Multi-Arch:",config.getstr('binaryMultiArch')
221                 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
222                 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
223                         config.get('binaryDepends', []))
224                 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
225                 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
226                 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
227                 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
228                 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
229                 print >>f, "Description:",sourceName,"(auto-debuild)"
230                 print >>f, " Package auto-generated by auto-debuild."
231                 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
232                 if dbgPackage:
233                         print >>f, ""
234                         print >>f, "Package:",binaryName+"-dbg"
235                         print >>f, "Section: debug"
236                         print >>f, "Priority: extra"
237                         print >>f, "Architecture:",packageArchitecture
238                         writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
239                         print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
240                         print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
241                         files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
242         # install file
243         with open('debian/'+binaryName+'.install', 'w') as f:
244                 for line in config.get('binaryInstallFiles', []):
245                         if line.startswith('/'): # a file from within the package, not from the source tree
246                                 line = 'debian/'+binaryName+line
247                         print >>f, line
248         # maintainer scripts for alternatives
249         if 'alternatives' in config:
250                 with open('debian/'+binaryName+'.postinst', 'w') as f:
251                         print >>f, "#!/bin/sh"
252                         print >>f, "set -e"
253                         print >>f, 'if [ "$1" = "configure" ]; then'
254                         for alternative in config.get('alternatives'):
255                                 print >>f, safeCall('update-alternatives', '--install', alternative['link'], alternative['name'], alternative['target'],
256                                         str(alternative['priority']))
257                         print >>f, 'fi'
258                         print >>f, ''
259                         print >>f, '#DEBHELPER#'
260                         print >>f, ''
261                         print >>f, 'exit 0'
262                 with open('debian/'+binaryName+'.prerm', 'w') as f:
263                         print >>f, "#!/bin/sh"
264                         print >>f, "set -e"
265                         print >>f, 'if [ "$1" = "remove" ]; then'
266                         for alternative in config.get('alternatives'):
267                                 print >>f, safeCall('update-alternatives', '--remove', alternative['name'], alternative['target'])
268                         print >>f, 'fi'
269                         print >>f, ''
270                         print >>f, '#DEBHELPER#'
271                         print >>f, ''
272                         print >>f, 'exit 0'
273         # rules file: build system specific
274         with open('debian/rules', 'w') as f:
275                 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
276                 r = buildSystem.ruleMaker(config)
277                 # global rules
278                 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
279                 if not dbgPackage:
280                         # disable debug information
281                         r.env["DEB_CFLAGS_APPEND"] = '-g0'
282                         r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
283                 r.dh += ['--parallel']
284                 if withPython2:
285                         r.dhWith.add('python2')
286                         r.rules['python2'] = ['dh_python2 --no-guessing-versions']
287                 r.rules['builddeb'] = [safeCall('dh_builddeb', "--destdir="+debDir)] # passing this gobally to dh results in weird problems (like stuff being installed there, and not in the package...)
288                 r.rules['auto_test'] = []
289                 # installation rule
290                 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
291                 if 'binarySkipFiles' in config:
292                         r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " +
293                                 safeCall('rm', *config.get('binarySkipFiles')))
294                 # for debug packages
295                 if dbgPackage:
296                         r.rules['strip'] = [safeCall('dh_strip', '--dbg-package='+binaryName+"-dbg")] # put debug files in appropriate package
297                         r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)] # make the doc folder of the dbg package a symlink
298                 # wait after configuration?
299                 if config.getbool('waitAfterConfig', False):
300                         if not 'auto_configure' in r.rules: r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override
301                         r.rules['auto_configure'].append("@"+safeCall('read', '-p', 'Configuration done. Hit "Enter" to build the package. ', 'DUMMY_VAR')) # if we run in dash, we need to tell it which variable to use for the result...
302                 # dump it to a file
303                 r.write(f)
304         mode = os.stat('debian/rules').st_mode
305         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
306         # return list of files that will be created
307         return files
308
309 def buildDebianPackage(config):
310         commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
311         command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
312         subprocess.check_call(commandInBuildEnv(config, command))
313         shutil.rmtree('debian') # it only contains what we just created
314
315 ###################################################################
316 # if we are called directly as script
317 if __name__ == "__main__":
318         try:
319                 # get config
320                 config = loadConfigFile('auto-debuild.conf')
321                 # generate debian files
322                 if os.path.exists('debian'):
323                         if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
324                                 sys.exit(1)
325                         shutil.rmtree('debian')
326                 files = createDebianFiles(config)
327                 # check if a file is overwritten
328                 for file in files:
329                         if os.path.exists(file):
330                                 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
331                                         sys.exit(1)
332                 # run compilation
333                 buildDebianPackage(config)
334                 # install files
335                 print "Installing created deb files..."
336                 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
337         except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
338                 print >> sys.stderr
339                 print >> sys.stderr
340                 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
341                         print >> sys.stderr, "Interruped by user"
342                 else:
343                         print >> sys.stderr, "Error during package creation: %s" % str(e)
344                 print >> sys.stderr
345                 sys.exit(1)