2 import os, shutil, stat, time, subprocess, sys
3 from collections import OrderedDict
5 # a dict with some useful additional getters which can convert types and handle one-element lists like their single member
6 class ConfigDict(dict):
7 def getstr(self, name, default = None):
8 if not name in self: return default
10 if isinstance(val, list):
11 if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
16 def getint(self, name, default = None):
17 return int(self.getstr(name, default))
19 def getbool(self, name, default = None):
20 val = self.getstr(name, default)
21 if isinstance(val, bool): return val # already a bool
22 return val.lower() in ('true', 'yes', 'on', '1')
24 # create a safe-to-call shell command from the array
28 assert arg.find("'") < 0 # ' is not supported
29 if len(res): res += " "
33 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
34 # Lines starting with spaces are continuation lines
35 def loadConfigFile(file):
39 with open(file) as file:
44 isCont = len(line) and line[0].isspace() # remember if we were a continuation line
45 if isCont and curKey is None:
46 raise Exception("Invalid config, line %d: Starting with continuation line" % linenr)
48 if not len(line) or line.startswith("#"): continue # skip empty and comment lines
52 result[curKey] += shlex.split(line)
55 pos = line.index("=") # will raise exception when substring is not found
56 curKey = line[:pos].strip()
57 result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
59 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
60 # add some convencience get functions
63 # representation of a build system
65 def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
66 self.ruleMaker = ruleMaker
67 self.buildDepends = buildDepends
68 self.binaryDepends = binaryDepends
70 # abstract representation of rules file
76 self.rules = OrderedDict()
80 for name in self.env: # we rely on the name being sane (i.e., no special characters)
82 assert val.find("'") < 0 # ' is not supported
83 if len(res): res += " "
84 res += name+"='"+val+"'"
88 print >>f, "#!/usr/bin/make -f"
90 print >>f, ".PHONY: build" # there may be a directory called "build"
92 print >>f, "build %:" # need to mention "build" here again explicitly so PHONY takes effect
93 # write proper dh call
96 dh.append('--with='+','.join(self.dhWith))
97 print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(*dh)
98 # write remaining rules
99 for rule in self.rules:
101 print >>f, "override_dh_"+rule+":"
102 for line in self.rules[rule]:
106 def cmakeRules(config):
107 buildDir = config.getstr('buildDir', 'build')
110 r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
111 r.rules['auto_configure'] = [
112 safeCall("mkdir", "-p", buildDir),
113 safeCall("cd", buildDir) + " && " +
114 safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
116 r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
119 def automakeRules(config):
120 # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
121 # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
122 # and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
124 r.dh += ["--buildsystem=autoconf"]
125 r.rules['auto_configure'] = [
126 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
127 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
128 './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
129 '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
130 '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
131 '--sysconfdir=/etc --localstatedir=/var '+
132 safeCall(*config.get('automakeParameters', []))
134 r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
137 def pythonRules(config):
139 r.dh += ["--buildsystem=python_distutils"]
140 r.dhWith.add('python2')
141 r.rules['auto_clean'] = [ # clean properly
147 def noneRules(config):
149 r.dh += ["--buildsystem=makefile"] # makefile does the last possible harm
150 r.rules['auto_build'] = []
155 'cmake': BuildSystem(cmakeRules, ["cmake"]),
156 'automake': BuildSystem(automakeRules),
157 'python': BuildSystem(pythonRules, ["python-setuptools"], ["${python:Depends}"]),
158 'none': BuildSystem(noneRules),
162 def commandInBuildEnv(config, command):
163 schroot = config.getstr('schroot')
164 if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
167 def getArchitecture(config):
168 cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
169 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
170 res = p.communicate()[0] # get only stdout
171 if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
172 return res[0:len(res)-1] # chop of the \n at the end
174 def writeDependency(f, name, list):
176 print >>f, name+": "+', '.join(list)
178 # actual work functions
179 def createDebianFiles(config):
180 if not isinstance(config, ConfigDict):
181 config = ConfigDict(config)
182 sourceName = config.getstr('sourceName')
183 binaryName = config.getstr('binaryName', sourceName+'-local')
184 name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
185 email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
186 debDir = os.path.expanduser(config.getstr('debDir'))
187 buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
188 version = config.getstr('version')
189 dbgPackage = config.getbool('dbgPackage', False)
190 parallelJobs = config.getint('parallelJobs', 2)
191 packageArchitecture = config.getstr('architecture', 'any')
192 withPython2 = config.getbool('withPython2', False)
194 buildSystem.binaryDepends.append("${python:Depends}") # HACK, but it works: make sure dependencies on binary are added
195 # we return the list of files generated, so we need to know the architecture
196 arch = getArchitecture(config)
199 if os.path.exists('debian'): raise Exception('debian folder already exists?')
201 os.mkdir('debian/source')
202 if not os.path.exists(debDir): os.makedirs(debDir)
204 with open('debian/source/format', 'w') as f:
205 print >>f, "3.0 (native)"
207 with open('debian/compat', 'w') as f:
210 with open('debian/copyright', 'w') as f:
211 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
213 with open('debian/changelog', 'w') as f:
214 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
216 print >>f, " * Auto-generated by auto-debuild"
218 print >>f, " --",name,"<"+email+"> "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
220 with open('debian/control', 'w') as f:
221 print >>f, "Source:",sourceName
222 print >>f, "Section:",config.getstr('section', 'misc')
223 print >>f, "Priority: extra"
224 print >>f, "Maintainer: %s <%s>" % (name, email)
225 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
226 print >>f, "Standards-Version: 3.9.3"
228 print >>f, "Package:",binaryName
229 print >>f, "Architecture:",packageArchitecture
230 if 'binaryMultiArch' in config:
231 print >>f, "Multi-Arch:",config.getstr('binaryMultiArch')
232 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
233 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
234 config.get('binaryDepends', []))
235 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
236 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
237 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
238 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
239 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
240 print >>f, "Description:",sourceName,"(auto-debuild)"
241 print >>f, " Package auto-generated by auto-debuild."
242 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
245 print >>f, "Package:",binaryName+"-dbg"
246 print >>f, "Section: debug"
247 print >>f, "Priority: extra"
248 print >>f, "Architecture:",packageArchitecture
249 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
250 print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
251 print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
252 files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
254 with open('debian/'+binaryName+'.install', 'w') as f:
255 for line in config.get('binaryInstallFiles', []):
256 if line.startswith('/'): # a file from within the package, not from the source tree
257 line = 'debian/'+binaryName+line
259 # maintainer scripts for alternatives
260 if 'alternatives' in config:
261 with open('debian/'+binaryName+'.postinst', 'w') as f:
262 print >>f, "#!/bin/sh"
264 print >>f, 'if [ "$1" = "configure" ]; then'
265 for alternative in config.get('alternatives'):
266 print >>f, safeCall('update-alternatives', '--install', alternative['link'], alternative['name'], alternative['target'],
267 str(alternative['priority']))
270 print >>f, '#DEBHELPER#'
273 with open('debian/'+binaryName+'.prerm', 'w') as f:
274 print >>f, "#!/bin/sh"
276 print >>f, 'if [ "$1" = "remove" ]; then'
277 for alternative in config.get('alternatives'):
278 print >>f, safeCall('update-alternatives', '--remove', alternative['name'], alternative['target'])
281 print >>f, '#DEBHELPER#'
284 # rules file: build system specific
285 with open('debian/rules', 'w') as f:
286 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
287 r = buildSystem.ruleMaker(config)
289 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
291 # disable debug information
292 r.env["DEB_CFLAGS_APPEND"] = '-g0'
293 r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
294 r.dh += ['--parallel']
296 r.dhWith.add('python2')
297 r.rules['python2'] = ['dh_python2 --no-guessing-versions']
298 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...)
299 r.rules['auto_test'] = []
301 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
302 if 'binarySkipFiles' in config:
303 r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " +
304 safeCall('rm', *config.get('binarySkipFiles')))
307 r.rules['strip'] = [safeCall('dh_strip', '--dbg-package='+binaryName+"-dbg")] # put debug files in appropriate package
308 r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)] # make the doc folder of the dbg package a symlink
309 # wait after configuration?
310 if config.getbool('waitAfterConfig', False):
311 if not 'auto_configure' in r.rules: r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override
312 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...
315 mode = os.stat('debian/rules').st_mode
316 os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
317 # return list of files that will be created
320 def buildDebianPackage(config):
321 if not isinstance(config, ConfigDict):
322 config = ConfigDict(config)
323 commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
324 command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
325 subprocess.check_call(commandInBuildEnv(config, command))
326 shutil.rmtree('debian') # it only contains what we just created
328 ###################################################################
329 # if we are called directly as script
330 if __name__ == "__main__":
333 config = loadConfigFile('auto-debuild.conf')
334 # generate debian files
335 if os.path.exists('debian'):
336 if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
338 shutil.rmtree('debian')
339 files = createDebianFiles(config)
340 # check if a file is overwritten
342 if os.path.exists(file):
343 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
346 buildDebianPackage(config)
348 print "Installing created deb files..."
349 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
350 except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
353 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
354 print >> sys.stderr, "Interruped by user"
356 print >> sys.stderr, "Error during package creation: %s" % str(e)