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