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
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 >>f, "#!/usr/bin/make -f"
106 print >>f, ".PHONY: build" # there may be a directory called "build"
108 print >>f, "build %:" # 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 >>f, '\t'+self.env2str()+' dh $@ '+safeCall(*dh)
114 # write remaining rules
115 for rule in self.rules:
117 print >>f, "override_dh_"+rule+":"
118 for line in self.rules[rule]:
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 # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
135 # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
136 # and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
137 r.dh += ["--buildsystem=autoconf"]
138 r.rules['auto_configure'] = [
139 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
140 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
141 './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
142 '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
143 '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
144 safeCall('--docdir=/usr/share/doc/'+config['binaryName'], '--sysconfdir=/etc', '--localstatedir=/var', *config.get('automakeParameters', []))
146 r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
148 def makefileRules(r, config):
149 r.dh += ["--buildsystem=makefile"]
150 r.rules['auto_configure'] = []
152 def noneRules(r, config):
153 r.dh += ["--buildsystem=makefile"] # makefile does the least possible harm
154 r.rules['auto_configure'] = []
155 r.rules['auto_build'] = []
156 r.rules['auto_clean'] = []
161 'cmake': BuildSystem(cmakeRules, ["cmake"]),
162 'automake': BuildSystem(automakeRules),
163 'makefile': BuildSystem(makefileRules),
164 'none': BuildSystem(noneRules),
168 def commandInBuildEnv(config, command):
169 schroot = config.getstr('schroot')
170 if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
173 def getArchitecture(config):
174 cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
175 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
176 res = p.communicate()[0] # get only stdout
177 if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
178 return res[0:len(res)-1] # chop of the \n at the end
180 def writeDependency(f, name, list):
182 print >>f, name+": "+', '.join(list)
184 # actual work functions
185 def createDebianFiles(config):
186 if not isinstance(config, ConfigDict):
187 config = ConfigDict(config)
188 sourceName = config.getstr('sourceName')
189 binaryName = config.getstr('binaryName', sourceName+'-local')
190 config['binaryName'] = binaryName # make it usable by build systems
191 name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
192 email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
193 debDir = os.path.expanduser(config.getstr('debDir'))
194 buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
195 version = config.getstr('version') # version name excluding epoch (used for filenames)
196 fullVersion = str(config.getint('epoch'))+':'+version if 'epoch' in config else version # version name including epoch
197 dbgPackage = config.getbool('dbgPackage', False)
198 parallelJobs = config.getint('parallelJobs', 2)
199 packageArchitecture = config.getstr('architecture', 'any')
200 withPython2 = config.getbool('withPython2', False)
201 withAutoreconf = config.getbool('withAutoreconf', False)
202 # add some build dependencies (a bit hacky adding it to the build system...)
204 buildSystem.binaryDepends.append("${python:Depends}")
206 buildSystem.binaryDepends.append("dh-autoreconf")
207 # we return the list of files generated, so we need to know the architecture
208 arch = getArchitecture(config)
211 if os.path.exists('debian'): raise Exception('debian folder already exists?')
213 os.mkdir('debian/source')
214 if not os.path.exists(debDir): os.makedirs(debDir)
216 with open('debian/source/format', 'w') as f:
217 print >>f, "3.0 (native)"
219 with open('debian/compat', 'w') as f:
222 with open('debian/copyright', 'w') as f:
223 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
225 with open('debian/changelog', 'w') as f:
226 print >>f, sourceName,"("+fullVersion+")","UNRELEASED; urgency=low"
228 print >>f, " * Auto-generated by auto-debuild"
230 print >>f, " --",name,"<"+email+"> "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
232 with open('debian/control', 'w') as f:
234 print >>f, "Source:",sourceName
235 print >>f, "Section:",config.getstr('section', 'misc')
236 print >>f, "Priority: extra"
237 print >>f, "Maintainer: %s <%s>" % (name, email)
238 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
239 print >>f, "Standards-Version: 3.9.3"
240 # main binary package
242 print >>f, "Package:",binaryName
243 print >>f, "Architecture:",packageArchitecture
244 if 'binaryMultiArch' in config:
245 print >>f, "Multi-Arch:",config.getstr('binaryMultiArch')
246 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
247 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
248 config.get('binaryDepends', []))
249 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
250 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
251 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
252 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
253 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
254 print >>f, "Description:",sourceName,"(auto-debuild)"
255 print >>f, " Package auto-generated by auto-debuild."
256 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
260 print >>f, "Package:",binaryName+"-dbg"
261 print >>f, "Section: debug"
262 print >>f, "Priority: extra"
263 print >>f, "Architecture:",packageArchitecture
264 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
265 print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
266 print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
267 files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
269 for shim in config.get('binaryShims', []):
271 print >>f, "Package:",shim
272 print >>f, "Section:",config.getstr('section', 'misc')
273 print >>f, "Priority: extra"
274 print >>f, "Architecture:",packageArchitecture
275 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
276 print >>f, "Description:",sourceName,"shim for",shim,"(auto-debuild)"
277 print >>f, " Package pretending to be "+shim+", auto-generated by auto-debuild."
278 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (shim, version, arch)))
280 with open('debian/'+binaryName+'.install', 'w') as f:
281 for line in config.get('binaryInstallFiles', []):
282 if line.startswith('/'): # a file from within the package, not from the source tree
283 line = 'debian/'+binaryName+line
285 # maintainer scripts for alternatives
286 if 'alternatives' in config:
287 with open('debian/'+binaryName+'.postinst', 'w') as f:
288 print >>f, "#!/bin/sh"
290 print >>f, 'if [ "$1" = "configure" ]; then'
291 for alternative in config.get('alternatives'):
292 alternative = shlex.split(alternative)
293 print >>f, safeCall('update-alternatives', '--install', alternative[0], alternative[1], alternative[2], alternative[3])
296 print >>f, '#DEBHELPER#'
299 with open('debian/'+binaryName+'.prerm', 'w') as f:
300 print >>f, "#!/bin/sh"
302 print >>f, 'if [ "$1" = "remove" ]; then'
303 for alternative in config.get('alternatives'):
304 alternative = shlex.split(alternative)
305 print >>f, safeCall('update-alternatives', '--remove', alternative[1], alternative[2])
308 print >>f, '#DEBHELPER#'
311 # rules file: build system specific
312 with open('debian/rules', 'w') as f:
313 # pre-fill rule file with our global defaults
315 r.rules['auto_test'] = []
316 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
317 r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override (we may just append to it later)
318 # patch rule file for build system: may only touch auto_* rules and the dh options
319 buildSystem.ruleMaker(r, config)
321 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
323 # disable debug information
324 r.env["DEB_CFLAGS_APPEND"] = '-g0'
325 r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
326 r.dh += ['--parallel']
328 r.dhWith.add('python2')
329 r.rules['python2'] = ['dh_python2 --no-guessing-versions --no-shebang-rewrite']
331 r.dhWith.add('autoreconf')
332 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...)
334 if 'binarySkipFiles' in config:
335 r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " + safeCall('rm', *config.get('binarySkipFiles')))
338 r.rules['strip'] = [safeCall('dh_strip', '--dbg-package='+binaryName+"-dbg")] # put debug files in appropriate package
339 # make the doc folder of the other packages a symlink (dbg, shims)
340 r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)]
341 # wait after configuration?
342 if config.getbool('waitAfterConfig', False):
343 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...
346 mode = os.stat('debian/rules').st_mode
347 os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
348 # return list of files that will be created
351 def buildDebianPackage(config):
352 if not isinstance(config, ConfigDict):
353 config = ConfigDict(config)
354 commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary']
355 command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
356 subprocess.check_call(commandInBuildEnv(config, command))
357 shutil.rmtree('debian') # cleanup: the debian folder only contains what we just created
359 ###################################################################
360 # if we are called directly as script
361 if __name__ == "__main__":
364 config = loadConfigFile('auto-debuild.conf')
365 # generate debian files
366 if os.path.exists('debian'):
367 if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
369 shutil.rmtree('debian')
370 files = createDebianFiles(config)
371 # check if a file is overwritten
373 if os.path.exists(file):
374 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
377 buildDebianPackage(config)
379 print "Installing created deb files..."
380 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
381 except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
384 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
385 print >> sys.stderr, "Interruped by user"
387 print >> sys.stderr, "Error during package creation: %s" % str(e)