+# create a safe-to-call shell command from the array
+def safeCall(*args):
+ res = ""
+ for arg in args:
+ assert arg.find("'") < 0 # ' is not supported
+ if len(res): res += " "
+ res += "'"+arg+"'"
+ return res
+
+# Load a section-less config file: maps parameter names to strings or lists of strings (which are comma-separated or in separate lines)
+# Lines starting with spaces are continuation lines
+def loadConfigFile(file):
+ import shlex
+ # read config file
+ linenr = 0
+ with open(file) as file:
+ result = AdvancedDict()
+ curKey = None
+ for line in file:
+ linenr += 1
+ isCont = len(line) and line[0].isspace() # remember if we were a continuation line
+ if isCont and curKey is None:
+ raise Exception("Invalid config, line %d: Starting with continuation line" % linenr)
+ line = line.strip()
+ if not len(line) or line.startswith("#"): continue # skip empty and comment lines
+ try:
+ if isCont:
+ # continuation line
+ result[curKey] += shlex.split(line)
+ else:
+ # option line
+ pos = line.index("=") # will raise exception when substring is not found
+ curKey = line[:pos].strip()
+ value = line[pos+1:]
+ result[curKey] = shlex.split(value)
+ except Exception:
+ raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
+ # add some convencience get functions
+ return result
+
+# representation of a build system
+class BuildSystem:
+ def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
+ self.ruleMaker = ruleMaker
+ self.buildDepends = buildDepends
+ self.binaryDepends = binaryDepends
+
+# abstract representation of rules file
+class RulesFile:
+ def __init__(self):
+ self.env = {}
+ self.dh = []
+ self.dhWith = set()
+ self.rules = OrderedDict()
+
+ def env2str(self):
+ res = ""
+ for name in self.env: # we rely on the name being sane (i.e., no special characters)
+ val = self.env[name]
+ assert val.find("'") < 0 # ' is not supported
+ if len(res): res += " "
+ res += name+"='"+val+"'"
+ return res
+
+ def write(self, f):
+ print >>f, "#!/usr/bin/make -f"
+ print >>f, ""
+ print >>f, ".PHONY: build" # there may be a directory called "build"
+ print >>f, ""
+ print >>f, "build %:" # need to mention "build" here again explicitly so PHONY takes effect
+ # write proper dh call
+ dh = self.dh
+ if self.dhWith:
+ dh.append('--with='+','.join(self.dhWith))
+ print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(*dh)
+ # write remaining rules
+ for rule in self.rules:
+ print >>f, ""
+ print >>f, "override_dh_"+rule+":"
+ for line in self.rules[rule]:
+ print >>f, "\t"+line
+
+# rule-makers
+def cmakeRules(config):
+ buildDir = config.getstr('buildDir', 'build')
+ srcDir = os.getcwd()
+ r = RulesFile()
+ r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
+ r.rules['auto_configure'] = [
+ safeCall("mkdir", "-p", buildDir),
+ safeCall("cd", buildDir) + " && " +
+ safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
+ ]
+ r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
+ return r
+
+def automakeRules(config):
+ # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
+ # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
+ # and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
+ r = RulesFile()
+ r.dh += ["--buildsystem=autoconf"]
+ r.rules['auto_configure'] = [
+ 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
+ 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
+ './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
+ '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
+ '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
+ '--sysconfdir=/etc --localstatedir=/var '+
+ safeCall(*config.get('automakeParameters', []))
+ ]
+ r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
+ return r
+
+def pythonRules(config):
+ r = RulesFile()
+ r.dh += ["--buildsystem=python_distutils"]
+ r.dhWith.add('python2')
+ r.rules['auto_clean'] = [ # clean properly
+ 'dh_auto_clean',
+ 'rm -rf build'
+ ]
+ return r
+
+# build systems
+buildSystems = {
+ 'cmake': BuildSystem(cmakeRules, ["cmake"]),
+ 'automake': BuildSystem(automakeRules),
+ 'python': BuildSystem(pythonRules, ["python-setuptools"], ["${python:Depends}"]),
+}
+
+# utility functions
+def commandInBuildEnv(config, command):
+ schroot = config.getstr('schroot')
+ if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
+ return command
+
+def getArchitecture(config):
+ cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ res = p.communicate()[0] # get only stdout
+ if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
+ return res[0:len(res)-1] # chop of the \n at the end
+
+def writeDependency(f, name, list):
+ if len(list):
+ print >>f, name+": "+', '.join(list)
+
+# actual work functions