we have to disable dh_usrlocal
[auto-debuild.git] / auto_debuild.py
1 #!/usr/bin/env python3
2 # auto-debuild - Automatic Generation of Debian Packages
3 # Copyright (C) 2012 Ralf Jung <post@ralfj.de>
4 #
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.
9 #
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.
14 #
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.
18
19 import os, shutil, stat, time, subprocess, sys, shlex, tempfile, argparse, multiprocessing
20 from collections import OrderedDict
21
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
26                 val = self[name]
27                 if isinstance(val, list):
28                         if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
29                         return val[0]
30                 else:
31                         return val
32         
33         def getint(self, name, default = None):
34                 return int(self.getstr(name, default))
35         
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')
40
41 # create a safe-to-call shell command from the array
42 def safeCall(*args):
43         res = ""
44         for arg in args:
45                 assert arg.find("'") < 0 # ' is not supported
46                 if len(res): res += " "
47                 res += "'"+arg+"'"
48         return res
49
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):
53         # read config file
54         linenr = 0
55         with open(file) as file:
56                 result = ConfigDict()
57                 curKey = None
58                 for line in file:
59                         linenr += 1
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)
63                         line = line.strip()
64                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
65                         try:
66                                 if isCont:
67                                         # continuation line
68                                         result[curKey] += shlex.split(line)
69                                 else:
70                                         # option 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
74                         except Exception:
75                                 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
76         # add some convencience get functions
77         return result
78
79 # representation of a build system
80 class BuildSystem:
81         def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
82                 self.ruleMaker = ruleMaker
83                 self.buildDepends = buildDepends
84                 self.binaryDepends = binaryDepends
85
86 # abstract representation of rules file
87 class RulesFile:
88         def __init__(self):
89                 self.env = {}
90                 self.dh = []
91                 self.dhWith = set()
92                 self.rules = OrderedDict()
93         
94         def env2str(self):
95                 res = ""
96                 for name in self.env: # we rely on the name being sane (i.e., no special characters)
97                         val = self.env[name]
98                         assert val.find("'") < 0 # ' is not supported
99                         if len(res): res += " "
100                         res += name+"='"+val+"'"
101                 return res
102
103         def write(self, f):
104                 print("#!/usr/bin/make -f", file=f)
105                 print(file=f)
106                 print("%:", file=f)
107                 # write proper dh call
108                 dh = self.dh
109                 if self.dhWith:
110                         dh.append('--with='+','.join(self.dhWith))
111                 print('\t'+self.env2str()+' dh $@ '+safeCall(*dh), file=f)
112                 # write remaining rules
113                 for rule in self.rules:
114                         print(file=f)
115                         print("override_dh_"+rule+":", file=f)
116                         for line in self.rules[rule]:
117                                 print("\t"+line, file=f)
118
119 # rule-makers
120 def cmakeRules(r, config):
121         buildDir = config.getstr('buildDir', 'build')
122         srcDir = os.getcwd()
123         r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
124         r.rules['auto_configure'] = [
125                 safeCall("mkdir", "-p", buildDir),
126                 safeCall("cd", buildDir) + " && " +
127                   safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
128         ]
129         r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
130
131 def automakeRules(r, config):
132         buildDir = config.getstr('buildDir', 'build')
133         srcDir = os.getcwd()
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 so, 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", "--builddirectory="+config.getstr('buildDir')]
138         r.rules['auto_configure'] = [
139         (safeCall(*config['autogen']) + " && " if 'autogen' in config else '') +
140                 safeCall("mkdir", "-p", buildDir),
141                 safeCall("cd", buildDir) + " && " +
142                 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
143                 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
144                 safeCall(srcDir+"/configure") +
145                         ' --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
146                         '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
147                         '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
148                         safeCall('--docdir=/usr/share/doc/'+config['binaryName'], '--sysconfdir=/etc', '--localstatedir=/var', *config.get('automakeParameters', []))
149         ]
150         r.rules['auto_clean'] = [safeCall("rm", "-f", "--", buildDir+"/config.status")] # do not re-use old configuration
151
152 def makefileRules(r, config):
153         r.dh += ["--buildsystem=makefile"]
154         r.rules['auto_configure'] = []
155
156 def noneRules(r, config):
157         r.dh += ["--buildsystem=makefile"] # makefile does the least possible harm
158         r.rules['auto_configure'] = []
159         r.rules['auto_build'] = []
160         r.rules['auto_clean'] = []
161         return r
162
163 # build systems
164 buildSystems = {
165         'cmake': BuildSystem(cmakeRules, ["cmake"]),
166         'automake': BuildSystem(automakeRules),
167         'makefile': BuildSystem(makefileRules),
168         'none': BuildSystem(noneRules),
169 }
170
171 # utility functions
172 def commandInBuildEnv(config, command):
173         schroot = config.getstr('schroot')
174         if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
175         return command
176
177 def getArchitecture(config):
178         cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
179         output = subprocess.check_output(cmd)
180         return output.decode('utf-8').strip('\n') # chop off the \n at the end
181
182 def writeDependency(f, name, list):
183         if len(list):
184                 print(name+": "+', '.join(list), file=f)
185
186 # actual work functions
187 def deleteDebianFolder():
188         if os.path.islink('debian'):
189                 target = os.readlink('debian')
190                 if os.path.exists(target):
191                         shutil.rmtree(target)
192                 os.remove('debian')
193         elif os.path.exists('debian'):
194                 shutil.rmtree('debian')
195
196 def createDebianFiles(config):
197         if not isinstance(config, ConfigDict):
198                 config = ConfigDict(config)
199         sourceName = config.getstr('sourceName')
200         binaryName = config.getstr('binaryName', sourceName+'-local')
201         config['binaryName'] = binaryName # make it usable by build systems
202         name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
203         email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
204         debDir = os.path.expanduser(config.getstr('debDir'))
205         buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
206         version = config.getstr('version') # version name excluding epoch (used for filenames)
207         fullVersion = str(config.getint('epoch'))+':'+version if 'epoch' in config else version # version name including epoch
208         parallelJobs = config.getint('parallelJobs', multiprocessing.cpu_count())
209         packageArchitecture = config.getstr('architecture', 'any')
210         withPython2 = config.getbool('withPython2', False)
211         withSIP = config.getbool('withSIP', False)
212         withAutoreconf = config.getbool('withAutoreconf', False)
213         # add some build dependencies (a bit hacky adding it to the build system...)
214         if withSIP:
215                 withPython2 = True
216                 buildSystem.buildDepends.append("python-sip")
217                 buildSystem.binaryDepends.append("${sip:Depends}")
218         if withPython2:
219                 buildSystem.buildDepends.append("python")
220                 buildSystem.binaryDepends.append("${python:Depends}")
221         if withAutoreconf:
222                 buildSystem.buildDepends.append("dh-autoreconf")
223         # we return the list of files generated, so we need to know the architecture
224         arch = getArchitecture(config)
225         files = []
226         # create folders
227         if os.path.exists('debian') or os.path.islink('debian'): raise Exception('debian folder already exists?')
228         if config.getbool('useTmp', True):
229                 tempdir = tempfile.mkdtemp(prefix='auto-debuild-')
230                 os.symlink(tempdir, 'debian')
231         else:
232                 os.mkdir('debian')
233         if not os.path.exists(debDir): os.makedirs(debDir)
234         # source format file
235         os.mkdir('debian/source')
236         with open('debian/source/format', 'w') as f:
237                 print("3.0 (native)", file=f)
238         # compat file
239         with open('debian/compat', 'w') as f:
240                 print("9", file=f)
241         # copyright file
242         with open('debian/copyright', 'w') as f:
243                 print("Auto-generated by auto-debuild, not suited for distribution", file=f)
244         # changelog file
245         with open('debian/changelog', 'w') as f:
246                 print(sourceName,"("+fullVersion+")","UNRELEASED; urgency=low", file=f)
247                 print(file=f)
248                 print("  * Auto-generated by auto-debuild", file=f)
249                 print(file=f)
250                 print(" --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z'), file=f)
251         # control file
252         with open('debian/control', 'w') as f:
253                 # source package
254                 print("Source:",sourceName, file=f)
255                 print("Section:",config.getstr('section', 'misc'), file=f)
256                 print("Priority: extra", file=f)
257                 print("Maintainer: %s <%s>" % (name, email), file=f)
258                 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
259                 print("Standards-Version: 3.9.3", file=f)
260                 # main binary package
261                 print(file=f)
262                 print("Package:",binaryName, file=f)
263                 print("Architecture:",packageArchitecture, file=f)
264                 if 'binaryMultiArch' in config:
265                         print("Multi-Arch:",config.getstr('binaryMultiArch'), file=f)
266                 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
267                 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
268                         config.get('binaryDepends', []))
269                 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
270                 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
271                 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
272                 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
273                 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
274                 print("Description:",sourceName,"(auto-debuild)", file=f)
275                 print(" Package auto-generated by auto-debuild.", file=f)
276                 files.append(os.path.join(debDir, "{}_{}_{}.deb".format(binaryName, version, arch)))
277                 files.append(os.path.join(debDir, "{}-dbgsym_{}_{}.deb".format(binaryName, version, arch)))
278                 # shim packages
279                 for shim in config.get('binaryShims', []):
280                         print(file=f)
281                         print("Package:",shim, file=f)
282                         print("Section:",config.getstr('section', 'misc'), file=f)
283                         print("Priority: extra", file=f)
284                         print("Architecture:",packageArchitecture, file=f)
285                         writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
286                         print("Description:",sourceName,"shim for",shim,"(auto-debuild)", file=f)
287                         print(" Package pretending to be "+shim+", auto-generated by auto-debuild.", file=f)
288                         files.append(os.path.join(debDir, "{}_{}_{}.deb".format(shim, version, arch)))
289         # install file
290         with open('debian/'+binaryName+'.install', 'w') as f:
291                 for line in config.get('binaryInstallFiles', []):
292                         if line.startswith('/'): # a file from within the package, not from the source tree
293                                 line = 'debian/'+binaryName+line
294                         print(line, file=f)
295         # maintainer scripts for alternatives
296         if 'alternatives' in config:
297                 with open('debian/'+binaryName+'.postinst', 'w') as f:
298                         print("#!/bin/sh", file=f)
299                         print("set -e", file=f)
300                         print('if [ "$1" = "configure" ]; then', file=f)
301                         for alternative in config.get('alternatives'):
302                                 alternative = shlex.split(alternative)
303                                 print(safeCall('update-alternatives', '--install', alternative[0], alternative[1], alternative[2], alternative[3]), file=f)
304                         print('fi', file=f)
305                         print(file=f)
306                         print('#DEBHELPER#', file=f)
307                         print(file=f)
308                         print('exit 0', file=f)
309                 with open('debian/'+binaryName+'.prerm', 'w') as f:
310                         print("#!/bin/sh", file=f)
311                         print("set -e", file=f)
312                         print('if [ "$1" = "remove" ]; then', file=f)
313                         for alternative in config.get('alternatives'):
314                                 alternative = shlex.split(alternative)
315                                 print(safeCall('update-alternatives', '--remove', alternative[1], alternative[2]), file=f)
316                         print('fi', file=f)
317                         print(file=f)
318                         print('#DEBHELPER#', file=f)
319                         print(file=f)
320                         print('exit 0', file=f)
321         # rules file: build system specific
322         with open('debian/rules', 'w') as f:
323                 # pre-fill rule file with our global defaults
324                 r = RulesFile()
325                 r.rules['auto_test'] = []
326                 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
327                 r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override (we may just append to it later)
328                 r.rules['usrlocal'] = [] # we *do* want to install things in /usr/local
329                 # patch rule file for build system: may only touch auto_* rules and the dh options
330                 buildSystem.ruleMaker(r, config)
331                 # global rules
332                 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
333                 r.dh += ['--parallel']
334                 if withPython2:
335                         r.dhWith.add('python2')
336                         r.rules['python2'] = ['dh_python2 --no-guessing-versions --no-shebang-rewrite']
337                         if withSIP:
338                                 r.rules['python2'].append(safeCall('dh_sip', '-p'+binaryName))
339                 if withAutoreconf:
340                         r.dhWith.add('autoreconf')
341                 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...)
342                 # installation rule
343                 if 'binarySkipFiles' in config:
344                         r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " + safeCall('rm', *config.get('binarySkipFiles')))
345                 # make the doc folder of the other packages a symlink (dbg, shims)
346                 r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)]
347                 # wait after configuration?
348                 if config.getbool('waitAfterConfig', False):
349                         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...
350                 # dump it to a file
351                 r.write(f)
352         mode = os.stat('debian/rules').st_mode
353         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
354         # return list of files that will be created
355         return files
356
357 def buildDebianPackage(config):
358         if not isinstance(config, ConfigDict):
359                 config = ConfigDict(config)
360         commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary']
361         command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
362         subprocess.check_call(commandInBuildEnv(config, command))
363         deleteDebianFolder() # cleanup: the debian folder only contains what we just created
364
365 ###################################################################
366 # if we are called directly as script
367 if __name__ == "__main__":
368         try:
369                 # read command-line arguments
370                 parser = argparse.ArgumentParser(description='Automatic Generation of Debian Packages')
371                 parser.add_argument("-w", "--wait-after-config",
372                                                         action="store_true", dest="wait_after_config",
373                                                         help="Wait for user confirmation after configuration is finished")
374                 args = parser.parse_args()
375                 # get config
376                 config = loadConfigFile('auto-debuild.conf')
377                 config['waitAfterConfig'] = args.wait_after_config
378                 # generate debian files
379                 if os.path.exists('debian') or os.path.islink('debian'):
380                         if input("A debian folder already exists, do you want to remove it and whatever it links to (y/N)? ").lower() != "y":
381                                 sys.exit(1)
382                         deleteDebianFolder()
383                 files = createDebianFiles(config)
384                 # check if a file is overwritten
385                 overwritten_files = list(filter(lambda file: os.path.exists(file), files))
386                 if overwritten_files:
387                         if input("Do you want to overwrite {} (y/N)? ".format(', '.join(overwritten_files))).lower() != "y":
388                                 sys.exit(1)
389                 # run compilation
390                 buildDebianPackage(config)
391                 # install files
392                 print("Installing created deb files...")
393                 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
394         except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
395                 print(file=sys.stderr)
396                 print(file=sys.stderr)
397                 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
398                         print("Interruped by user", file=sys.stderr)
399                 else:
400                         print("Error during package creation: %s" % str(e), file=sys.stderr)
401                 print(file=sys.stderr)
402                 sys.exit(1)