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