2 # auto-debuild - Automatic Generation of Debian Packages
3 # Copyright (C) 2012 Ralf Jung <post@ralfj.de>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 import os, shutil, stat, time, subprocess, sys, shlex, tempfile, argparse
20 from collections import OrderedDict
22 # a dict with some useful additional getters which can convert types and handle one-element lists like their single member
23 class ConfigDict(dict):
24 def getstr(self, name, default = None):
25 if not name in self: return default
27 if isinstance(val, list):
28 if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
33 def getint(self, name, default = None):
34 return int(self.getstr(name, default))
36 def getbool(self, name, default = None):
37 val = self.getstr(name, default)
38 if isinstance(val, bool): return val # already a bool
39 return val.lower() in ('true', 'yes', 'on', '1')
41 # create a safe-to-call shell command from the array
45 assert arg.find("'") < 0 # ' is not supported
46 if len(res): res += " "
50 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
51 # Lines starting with spaces are continuation lines
52 def loadConfigFile(file):
55 with open(file) as file:
60 isCont = len(line) and line[0].isspace() # remember if we were a continuation line
61 if isCont and curKey is None:
62 raise Exception("Invalid config, line %d: Starting with continuation line" % linenr)
64 if not len(line) or line.startswith("#"): continue # skip empty and comment lines
68 result[curKey] += shlex.split(line)
71 pos = line.index("=") # will raise exception when substring is not found
72 curKey = line[:pos].strip()
73 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
75 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
76 # add some convencience get functions
79 # representation of a build system
81 def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
82 self.ruleMaker = ruleMaker
83 self.buildDepends = buildDepends
84 self.binaryDepends = binaryDepends
86 # abstract representation of rules file
92 self.rules = OrderedDict()
96 for name in self.env: # we rely on the name being sane (i.e., no special characters)
98 assert val.find("'") < 0 # ' is not supported
99 if len(res): res += " "
100 res += name+"='"+val+"'"
104 print("#!/usr/bin/make -f", file=f)
106 print(".PHONY: build", file=f) # there may be a directory called "build"
108 print("build %:", file=f) # need to mention "build" here again explicitly so PHONY takes effect
109 # write proper dh call
112 dh.append('--with='+','.join(self.dhWith))
113 print('\t'+self.env2str()+' dh $@ '+safeCall(*dh), file=f)
114 # write remaining rules
115 for rule in self.rules:
117 print("override_dh_"+rule+":", file=f)
118 for line in self.rules[rule]:
119 print("\t"+line, file=f)
122 def cmakeRules(r, config):
123 buildDir = config.getstr('buildDir', 'build')
125 r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
126 r.rules['auto_configure'] = [
127 safeCall("mkdir", "-p", buildDir),
128 safeCall("cd", buildDir) + " && " +
129 safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
131 r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
133 def automakeRules(r, config):
134 buildDir = config.getstr('buildDir', 'build')
136 # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
137 # also, we don't really support cross-building... ;-) (to do so, we'd have to write shell code that checks whether BUILD_GNU_TYPE
138 # and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
139 r.dh += ["--buildsystem=autoconf", "--builddirectory="+config.getstr('buildDir')]
140 r.rules['auto_configure'] = [
141 safeCall("mkdir", "-p", buildDir),
142 safeCall("cd", buildDir) + " && " +
143 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
144 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
145 safeCall(srcDir+"/configure") +
146 ' --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
147 '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
148 '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
149 safeCall('--docdir=/usr/share/doc/'+config['binaryName'], '--sysconfdir=/etc', '--localstatedir=/var', *config.get('automakeParameters', []))
151 r.rules['auto_clean'] = [safeCall("rm", "-f", "--", buildDir+"/config.status")] # do not re-use old configuration
153 def makefileRules(r, config):
154 r.dh += ["--buildsystem=makefile"]
155 r.rules['auto_configure'] = []
157 def noneRules(r, config):
158 r.dh += ["--buildsystem=makefile"] # makefile does the least possible harm
159 r.rules['auto_configure'] = []
160 r.rules['auto_build'] = []
161 r.rules['auto_clean'] = []
166 'cmake': BuildSystem(cmakeRules, ["cmake"]),
167 'automake': BuildSystem(automakeRules),
168 'makefile': BuildSystem(makefileRules),
169 'none': BuildSystem(noneRules),
173 def commandInBuildEnv(config, command):
174 schroot = config.getstr('schroot')
175 if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
178 def getArchitecture(config):
179 cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
180 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
181 res = p.communicate()[0] # get only stdout
182 if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
183 return res[0:len(res)-1] # chop of the \n at the end
185 def writeDependency(f, name, list):
187 print(name+": "+', '.join(list), file=f)
189 def deleteDebianFolder():
190 if os.path.islink('debian'):
191 target = os.readlink('debian')
192 if os.path.exists(target):
193 shutil.rmtree(target)
196 shutil.rmtree('debian')
198 # actual work functions
199 def createDebianFiles(config):
200 if not isinstance(config, ConfigDict):
201 config = ConfigDict(config)
202 sourceName = config.getstr('sourceName')
203 binaryName = config.getstr('binaryName', sourceName+'-local')
204 config['binaryName'] = binaryName # make it usable by build systems
205 name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
206 email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
207 debDir = os.path.expanduser(config.getstr('debDir'))
208 buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
209 version = config.getstr('version') # version name excluding epoch (used for filenames)
210 fullVersion = str(config.getint('epoch'))+':'+version if 'epoch' in config else version # version name including epoch
211 dbgPackage = config.getbool('dbgPackage', False)
212 parallelJobs = config.getint('parallelJobs', 2)
213 packageArchitecture = config.getstr('architecture', 'any')
214 withPython2 = config.getbool('withPython2', False)
215 withSIP = config.getbool('withSIP', False)
216 withAutoreconf = config.getbool('withAutoreconf', False)
217 # add some build dependencies (a bit hacky adding it to the build system...)
220 buildSystem.buildDepends.append("python-sip")
221 buildSystem.binaryDepends.append("${sip:Depends}")
223 buildSystem.buildDepends.append("python")
224 buildSystem.binaryDepends.append("${python:Depends}")
226 buildSystem.buildDepends.append("dh-autoreconf")
227 # we return the list of files generated, so we need to know the architecture
228 arch = getArchitecture(config)
231 if os.path.exists('debian') or os.path.islink('debian'): raise Exception('debian folder already exists?')
232 if config.getbool('useTmp', True):
233 tempdir = tempfile.mkdtemp(prefix='auto-debuild-')
234 os.symlink(tempdir, 'debian')
237 if not os.path.exists(debDir): os.makedirs(debDir)
239 os.mkdir('debian/source')
240 with open('debian/source/format', 'w') as f:
241 print("3.0 (native)", file=f)
243 with open('debian/compat', 'w') as f:
246 with open('debian/copyright', 'w') as f:
247 print("Auto-generated by auto-debuild, not suited for distribution", file=f)
249 with open('debian/changelog', 'w') as f:
250 print(sourceName,"("+fullVersion+")","UNRELEASED; urgency=low", file=f)
252 print(" * Auto-generated by auto-debuild", file=f)
254 print(" --",name,"<"+email+"> "+time.strftime('%a, %d %b %Y %H:%M:%S %z'), file=f)
256 with open('debian/control', 'w') as f:
258 print("Source:",sourceName, file=f)
259 print("Section:",config.getstr('section', 'misc'), file=f)
260 print("Priority: extra", file=f)
261 print("Maintainer: %s <%s>" % (name, email), file=f)
262 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
263 print("Standards-Version: 3.9.3", file=f)
264 # main binary package
266 print("Package:",binaryName, file=f)
267 print("Architecture:",packageArchitecture, file=f)
268 if 'binaryMultiArch' in config:
269 print("Multi-Arch:",config.getstr('binaryMultiArch'), file=f)
270 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
271 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
272 config.get('binaryDepends', []))
273 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
274 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
275 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
276 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
277 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
278 print("Description:",sourceName,"(auto-debuild)", file=f)
279 print(" Package auto-generated by auto-debuild.", file=f)
280 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
284 print("Package:",binaryName+"-dbg", file=f)
285 print("Section: debug", file=f)
286 print("Priority: extra", file=f)
287 print("Architecture:",packageArchitecture, file=f)
288 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
289 print("Description:",sourceName,"debug smbols (auto-debuild)", file=f)
290 print(" Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild.", file=f)
291 files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
293 for shim in config.get('binaryShims', []):
295 print("Package:",shim, file=f)
296 print("Section:",config.getstr('section', 'misc'), file=f)
297 print("Priority: extra", file=f)
298 print("Architecture:",packageArchitecture, file=f)
299 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
300 print("Description:",sourceName,"shim for",shim,"(auto-debuild)", file=f)
301 print(" Package pretending to be "+shim+", auto-generated by auto-debuild.", file=f)
302 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (shim, version, arch)))
304 with open('debian/'+binaryName+'.install', 'w') as f:
305 for line in config.get('binaryInstallFiles', []):
306 if line.startswith('/'): # a file from within the package, not from the source tree
307 line = 'debian/'+binaryName+line
309 # maintainer scripts for alternatives
310 if 'alternatives' in config:
311 with open('debian/'+binaryName+'.postinst', 'w') as f:
312 print("#!/bin/sh", file=f)
313 print("set -e", file=f)
314 print('if [ "$1" = "configure" ]; then', file=f)
315 for alternative in config.get('alternatives'):
316 alternative = shlex.split(alternative)
317 print(safeCall('update-alternatives', '--install', alternative[0], alternative[1], alternative[2], alternative[3]), file=f)
320 print('#DEBHELPER#', file=f)
322 print('exit 0', file=f)
323 with open('debian/'+binaryName+'.prerm', 'w') as f:
324 print("#!/bin/sh", file=f)
325 print("set -e", file=f)
326 print('if [ "$1" = "remove" ]; then', file=f)
327 for alternative in config.get('alternatives'):
328 alternative = shlex.split(alternative)
329 print(safeCall('update-alternatives', '--remove', alternative[1], alternative[2]), file=f)
332 print('#DEBHELPER#', file=f)
334 print('exit 0', file=f)
335 # rules file: build system specific
336 with open('debian/rules', 'w') as f:
337 # pre-fill rule file with our global defaults
339 r.rules['auto_test'] = []
340 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
341 r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override (we may just append to it later)
342 # patch rule file for build system: may only touch auto_* rules and the dh options
343 buildSystem.ruleMaker(r, config)
345 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
347 # disable debug information
348 r.env["DEB_CFLAGS_APPEND"] = '-g0'
349 r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
350 r.dh += ['--parallel']
352 r.dhWith.add('python2')
353 r.rules['python2'] = ['dh_python2 --no-guessing-versions --no-shebang-rewrite']
355 r.rules['python2'].append(safeCall('dh_sip', '-p'+binaryName))
357 r.dhWith.add('autoreconf')
358 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...)
360 if 'binarySkipFiles' in config:
361 r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " + safeCall('rm', *config.get('binarySkipFiles')))
364 r.rules['strip'] = [safeCall('dh_strip', '--dbg-package='+binaryName+"-dbg")] # put debug files in appropriate package
365 # make the doc folder of the other packages a symlink (dbg, shims)
366 r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)]
367 # wait after configuration?
368 if config.getbool('waitAfterConfig', False):
369 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...
372 mode = os.stat('debian/rules').st_mode
373 os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
374 # return list of files that will be created
377 def buildDebianPackage(config):
378 if not isinstance(config, ConfigDict):
379 config = ConfigDict(config)
380 commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary']
381 command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
382 subprocess.check_call(commandInBuildEnv(config, command))
383 deleteDebianFolder() # cleanup: the debian folder only contains what we just created
385 ###################################################################
386 # if we are called directly as script
387 if __name__ == "__main__":
389 # read command-line arguments
390 parser = argparse.ArgumentParser(description='Automatic Generation of Debian Packages')
391 parser.add_argument("-w", "--wait-after-config",
392 action="store_true", dest="wait_after_config",
393 help="Wait for user confirmation after configuration is finished")
394 args = parser.parse_args()
396 config = loadConfigFile('auto-debuild.conf')
397 config['waitAfterConfig'] = args.wait_after_config
398 # generate debian files
399 if os.path.exists('debian') or os.path.islink('debian'):
400 if input("A debian folder already exists, do you want to remove it and whatever it links to (y/N)? ").lower() != "y":
403 files = createDebianFiles(config)
404 # check if a file is overwritten
406 if os.path.exists(file):
407 if input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
410 buildDebianPackage(config)
412 print("Installing created deb files...")
413 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
414 except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
415 print(file=sys.stderr)
416 print(file=sys.stderr)
417 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
418 print("Interruped by user", file=sys.stderr)
420 print("Error during package creation: %s" % str(e), file=sys.stderr)
421 print(file=sys.stderr)