2 import os, shutil, stat, time, subprocess, sys
3 from collections import OrderedDict
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
10 if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
13 def getint(self, name, default = None):
14 return int(self.getstr(name, default))
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')
21 # create a safe-to-call shell command from the array
25 assert arg.find("'") < 0 # ' is not supported
26 if len(res): res += " "
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):
35 with open(file) as file:
36 result = AdvancedDict()
39 isCont = len(line) and line[0].isspace() # remember if we were a continuation line
40 if isCont and curKey is None:
41 raise Exception("Invalid config: Starting with continuation line")
43 if not len(line) or line.startswith("#"): continue # skip empty and comment lines
46 result[curKey].append(shlex.split(line))
49 pos = line.index("=") # will raise exception when substring is not found
50 curKey = line[:pos].strip()
52 result[curKey] = shlex.split(value)
53 # add some convencience get functions
56 # representation of a build system
58 def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
59 self.ruleMaker = ruleMaker
60 self.buildDepends = buildDepends
61 self.binaryDepends = binaryDepends
63 # abstract representation of rules file
69 self.rules = OrderedDict()
73 for name in self.env: # we rely on the name being sane (i.e., no special characters)
75 assert val.find("'") < 0 # ' is not supported
76 if len(res): res += " "
77 res += name+"='"+val+"'"
81 print >>f, "#!/usr/bin/make -f"
83 print >>f, ".PHONY: build" # there may be a directory called "build"
85 print >>f, "build %:" # need to mention "build" here again explicitly
86 # write proper dh call
89 dh.append('--with='+','.join(self.dhWith))
90 print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(*dh)
91 # write remaining rules
92 for rule in self.rules:
94 print >>f, "override_dh_"+rule+":"
95 for line in self.rules[rule]:
99 def cmakeRules(config):
100 buildDir = config.getstr('buildDir', 'build')
103 r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
104 r.rules['auto_configure'] = [
105 safeCall("mkdir", "-p", buildDir),
106 safeCall("cd", buildDir) + " && " +
107 safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
109 r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
112 def automakeRules(config):
113 # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
114 # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
115 # and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
117 r.dh += ["--buildsystem=autoconf"]
118 r.rules['auto_configure'] = [
119 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
120 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
121 './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
122 '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
123 '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
124 '--sysconfdir=/etc --localstatedir=/var '+
125 safeCall(*config.get('automakeParameters', []))
127 r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
130 def pythonRules(config):
132 r.dh += ["--buildsystem=python_distutils"]
133 r.dhWith.add('python2')
134 r.rules['auto_clean'] = [ # clean properly
142 'cmake': BuildSystem(cmakeRules, ["cmake"]),
143 'automake': BuildSystem(automakeRules),
144 'python': BuildSystem(pythonRules, ["python-setuptools"], ["${python:Depends}"]),
148 def commandInBuildEnv(config, command):
149 schroot = config.getstr('schroot')
150 if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
153 def getArchitecture(config):
154 cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
155 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
156 res = p.communicate()[0] # get only stdout
157 if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
158 return res[0:len(res)-1] # chop of the \n at the end
160 def writeDependency(f, name, list):
162 print >>f, name+": "+', '.join(list)
164 # actual work functions
165 def createDebianFiles(config):
166 sourceName = config.getstr('sourceName')
167 binaryName = config.getstr('binaryName', sourceName+'-local')
168 name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
169 email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
170 debDir = os.path.expanduser(config.getstr('debDir'))
171 buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
172 version = config.getstr('version')
173 dbgPackage = config.getbool('dbgPackage', False)
174 parallelJobs = config.getint('parallelJobs', 2)
175 packageArchitecture = config.getstr('architecture', 'any')
176 withPython2 = config.getbool('withPython2', False)
178 buildSystem.binaryDepends.append("${python:Depends}") # HACK, but it works: make sure dependencies on binary are added
179 # we return the list of files generated, so we need to know the architecture
180 arch = getArchitecture(config)
183 if os.path.exists('debian'): raise Exception('debian folder already exists?')
185 os.mkdir('debian/source')
186 if not os.path.exists(debDir): os.makedirs(debDir)
188 with open('debian/source/format', 'w') as f:
189 print >>f, "3.0 (native)"
191 with open('debian/compat', 'w') as f:
194 with open('debian/copyright', 'w') as f:
195 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
197 with open('debian/changelog', 'w') as f:
198 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
200 print >>f, " * Auto-generated by auto-debuild"
202 print >>f, " --",name,"<"+email+"> "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
204 with open('debian/control', 'w') as f:
205 print >>f, "Source:",sourceName
206 print >>f, "Section:",config.getstr('section', 'misc')
207 print >>f, "Priority: extra"
208 print >>f, "Maintainer: %s <%s>" % (name, email)
209 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
210 print >>f, "Standards-Version: 3.9.3"
212 print >>f, "Package:",binaryName
213 print >>f, "Architecture:",packageArchitecture
214 if 'binaryMultiArch' in config:
215 print >>f, "Multi-Arch:",config.getstr('binaryMultiArch')
216 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
217 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
218 config.get('binaryDepends', []))
219 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
220 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
221 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
222 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
223 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
224 print >>f, "Description:",sourceName,"(auto-debuild)"
225 print >>f, " Package auto-generated by auto-debuild."
226 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
229 print >>f, "Package:",binaryName+"-dbg"
230 print >>f, "Section: debug"
231 print >>f, "Priority: extra"
232 print >>f, "Architecture:",packageArchitecture
233 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
234 print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
235 print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
236 files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
238 with open('debian/'+binaryName+'.install', 'w') as f:
239 for line in config.get('binaryInstallFiles', []):
240 if line.startswith('/'): # a file from within the package, not from the source tree
241 line = 'debian/'+binaryName+line
243 # maintainer scripts for alternatives
244 if 'alternatives' in config:
245 with open('debian/'+binaryName+'.postinst', 'w') as f:
246 print >>f, "#!/bin/sh"
248 print >>f, 'if [ "$1" = "configure" ]; then'
249 for alternative in config.get('alternatives'):
250 print >>f, safeCall('update-alternatives', '--install', alternative['link'], alternative['name'], alternative['target'],
251 str(alternative['priority']))
254 print >>f, '#DEBHELPER#'
257 with open('debian/'+binaryName+'.prerm', 'w') as f:
258 print >>f, "#!/bin/sh"
260 print >>f, 'if [ "$1" = "remove" ]; then'
261 for alternative in config.get('alternatives'):
262 print >>f, safeCall('update-alternatives', '--remove', alternative['name'], alternative['target'])
265 print >>f, '#DEBHELPER#'
268 # rules file: build system specific
269 with open('debian/rules', 'w') as f:
270 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
271 r = buildSystem.ruleMaker(config)
273 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
275 # disable debug information
276 r.env["DEB_CFLAGS_APPEND"] = '-g0'
277 r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
278 r.dh += ['--parallel']
280 r.dhWith.add('python2')
281 r.rules['python2'] = ['dh_python2 --no-guessing-versions']
282 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...)
283 r.rules['auto_test'] = []
285 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
286 if 'binarySkipFiles' in config:
287 r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " +
288 safeCall('rm', *config.get('binarySkipFiles')))
291 r.rules['strip'] = [safeCall('dh_strip', '--dbg-package='+binaryName+"-dbg")] # put debug files in appropriate package
292 r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)] # make the doc folder of the dbg package a symlink
293 # wait after configuration?
294 if config.getbool('waitAfterConfig', False):
295 if not 'auto_configure' in r.rules: r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override
296 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...
299 mode = os.stat('debian/rules').st_mode
300 os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
301 # return list of files that will be created
304 def buildDebianPackage(config):
305 commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
306 command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
307 subprocess.check_call(commandInBuildEnv(config, command))
308 shutil.rmtree('debian') # it only contains what we just created
310 ###################################################################
311 # if we are called directly as script
312 if __name__ == "__main__":
315 config = loadConfigFile('auto-debuild.conf')
316 # generate debian files
317 if os.path.exists('debian'):
318 if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
320 shutil.rmtree('debian')
321 files = createDebianFiles(config)
322 # check if a file is overwritten
324 if os.path.exists(file):
325 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
328 buildDebianPackage(config)
330 print "Installing created deb files..."
331 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
332 except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
335 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
336 print >> sys.stderr, "Interruped by user"
338 print >> sys.stderr, "Error during package creation: %s" % str(e)