5733273c4634e92ca33779b8ba4d730c99b427b3
[auto-debuild.git] / auto_debuild.py
1 #!/usr/bin/python
2 import os, shutil, stat, time, subprocess, sys, shlex
3 from collections import OrderedDict
4
5 # a dict with some useful additional getters which can convert types and handle one-element lists like their single member
6 class ConfigDict(dict):
7         def getstr(self, name, default = None):
8                 if not name in self: return default
9                 val = self[name]
10                 if isinstance(val, list):
11                         if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
12                         return val[0]
13                 else:
14                         return val
15         
16         def getint(self, name, default = None):
17                 return int(self.getstr(name, default))
18         
19         def getbool(self, name, default = None):
20                 val = self.getstr(name, default)
21                 if isinstance(val, bool): return val # already a bool
22                 return val.lower() in ('true', 'yes', 'on', '1')
23
24 # create a safe-to-call shell command from the array
25 def safeCall(*args):
26         res = ""
27         for arg in args:
28                 assert arg.find("'") < 0 # ' is not supported
29                 if len(res): res += " "
30                 res += "'"+arg+"'"
31         return res
32
33 # Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
34 # Lines starting with spaces are continuation lines
35 def loadConfigFile(file):
36         # read config file
37         linenr = 0
38         with open(file) as file:
39                 result = ConfigDict()
40                 curKey = None
41                 for line in file:
42                         linenr += 1
43                         isCont = len(line) and line[0].isspace() # remember if we were a continuation line
44                         if isCont and curKey is None:
45                                 raise Exception("Invalid config, line %d: Starting with continuation line" % linenr)
46                         line = line.strip()
47                         if not len(line) or line.startswith("#"): continue # skip empty and comment lines
48                         try:
49                                 if isCont:
50                                         # continuation line
51                                         result[curKey] += shlex.split(line)
52                                 else:
53                                         # option line
54                                         pos = line.index("=") # will raise exception when substring is not found
55                                         curKey = line[:pos].strip()
56                                         result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
57                         except Exception:
58                                 raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
59         # add some convencience get functions
60         return result
61
62 # representation of a build system
63 class BuildSystem:
64         def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
65                 self.ruleMaker = ruleMaker
66                 self.buildDepends = buildDepends
67                 self.binaryDepends = binaryDepends
68
69 # abstract representation of rules file
70 class RulesFile:
71         def __init__(self):
72                 self.env = {}
73                 self.dh = []
74                 self.dhWith = set()
75                 self.rules = OrderedDict()
76         
77         def env2str(self):
78                 res = ""
79                 for name in self.env: # we rely on the name being sane (i.e., no special characters)
80                         val = self.env[name]
81                         assert val.find("'") < 0 # ' is not supported
82                         if len(res): res += " "
83                         res += name+"='"+val+"'"
84                 return res
85
86         def write(self, f):
87                 print >>f, "#!/usr/bin/make -f"
88                 print >>f, ""
89                 print >>f, ".PHONY: build" # there may be a directory called "build"
90                 print >>f, ""
91                 print >>f, "build %:" # need to mention "build" here again explicitly so PHONY takes effect
92                 # write proper dh call
93                 dh = self.dh
94                 if self.dhWith:
95                         dh.append('--with='+','.join(self.dhWith))
96                 print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(*dh)
97                 # write remaining rules
98                 for rule in self.rules:
99                         print >>f, ""
100                         print >>f, "override_dh_"+rule+":"
101                         for line in self.rules[rule]:
102                                 print >>f, "\t"+line
103
104 # rule-makers
105 def cmakeRules(config):
106         buildDir = config.getstr('buildDir', 'build')
107         srcDir = os.getcwd()
108         r = RulesFile()
109         r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
110         r.rules['auto_configure'] = [
111                 safeCall("mkdir", "-p", buildDir),
112                 safeCall("cd", buildDir) + " && " +
113                   safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
114         ]
115         r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache
116         return r
117
118 def automakeRules(config):
119         # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
120         # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
121         #  and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
122         r = RulesFile()
123         r.dh += ["--buildsystem=autoconf"]
124         r.rules['auto_configure'] = [
125                 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
126                 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
127                         './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
128                         '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
129                         '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
130                         '--sysconfdir=/etc --localstatedir=/var '+
131                         safeCall(*config.get('automakeParameters', []))
132         ]
133         r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
134         return r
135
136 def pythonRules(config):
137         r = RulesFile()
138         r.dh += ["--buildsystem=python_distutils"]
139         r.dhWith.add('python2')
140         r.rules['auto_clean'] = [ # clean properly
141                 'dh_auto_clean',
142                 'rm -rf build'
143         ]
144         return r
145
146 def noneRules(config):
147         r = RulesFile()
148         r.dh += ["--buildsystem=makefile"] # makefile does the last possible harm
149         r.rules['auto_build'] = []
150         return r
151
152 # build systems
153 buildSystems = {
154         'cmake': BuildSystem(cmakeRules, ["cmake"]),
155         'automake': BuildSystem(automakeRules),
156         'python': BuildSystem(pythonRules, ["python-setuptools"], ["${python:Depends}"]),
157         'none': BuildSystem(noneRules),
158 }
159
160 # utility functions
161 def commandInBuildEnv(config, command):
162         schroot = config.getstr('schroot')
163         if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
164         return command
165
166 def getArchitecture(config):
167         cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
168         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
169         res = p.communicate()[0] # get only stdout
170         if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
171         return res[0:len(res)-1] # chop of the \n at the end
172
173 def writeDependency(f, name, list):
174         if len(list):
175                 print >>f, name+": "+', '.join(list)
176
177 # actual work functions
178 def createDebianFiles(config):
179         if not isinstance(config, ConfigDict):
180                 config = ConfigDict(config)
181         sourceName = config.getstr('sourceName')
182         binaryName = config.getstr('binaryName', sourceName+'-local')
183         name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
184         email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
185         debDir = os.path.expanduser(config.getstr('debDir'))
186         buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
187         version = config.getstr('version')
188         dbgPackage = config.getbool('dbgPackage', False)
189         parallelJobs = config.getint('parallelJobs', 2)
190         packageArchitecture = config.getstr('architecture', 'any')
191         withPython2 = config.getbool('withPython2', False)
192         if withPython2:
193                 buildSystem.binaryDepends.append("${python:Depends}") # HACK, but it works: make sure dependencies on binary are added
194         # we return the list of files generated, so we need to know the architecture
195         arch = getArchitecture(config)
196         files = []
197         # create folders
198         if os.path.exists('debian'): raise Exception('debian folder already exists?')
199         os.mkdir('debian')
200         os.mkdir('debian/source')
201         if not os.path.exists(debDir): os.makedirs(debDir)
202         # source format file
203         with open('debian/source/format', 'w') as f:
204                 print >>f, "3.0 (native)"
205         # compat file
206         with open('debian/compat', 'w') as f:
207                 print >>f, "9"
208         # copyright file
209         with open('debian/copyright', 'w') as f:
210                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
211         # changelog file
212         with open('debian/changelog', 'w') as f:
213                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
214                 print >>f, ""
215                 print >>f, "  * Auto-generated by auto-debuild"
216                 print >>f, ""
217                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
218         # control file
219         with open('debian/control', 'w') as f:
220                 print >>f, "Source:",sourceName
221                 print >>f, "Section:",config.getstr('section', 'misc')
222                 print >>f, "Priority: extra"
223                 print >>f, "Maintainer: %s <%s>" % (name, email)
224                 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
225                 print >>f, "Standards-Version: 3.9.3"
226                 print >>f, ""
227                 print >>f, "Package:",binaryName
228                 print >>f, "Architecture:",packageArchitecture
229                 if 'binaryMultiArch' in config:
230                         print >>f, "Multi-Arch:",config.getstr('binaryMultiArch')
231                 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
232                 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
233                         config.get('binaryDepends', []))
234                 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
235                 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
236                 writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
237                 writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
238                 writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
239                 print >>f, "Description:",sourceName,"(auto-debuild)"
240                 print >>f, " Package auto-generated by auto-debuild."
241                 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
242                 if dbgPackage:
243                         print >>f, ""
244                         print >>f, "Package:",binaryName+"-dbg"
245                         print >>f, "Section: debug"
246                         print >>f, "Priority: extra"
247                         print >>f, "Architecture:",packageArchitecture
248                         writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
249                         print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
250                         print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
251                         files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
252         # install file
253         with open('debian/'+binaryName+'.install', 'w') as f:
254                 for line in config.get('binaryInstallFiles', []):
255                         if line.startswith('/'): # a file from within the package, not from the source tree
256                                 line = 'debian/'+binaryName+line
257                         print >>f, line
258         # maintainer scripts for alternatives
259         if 'alternatives' in config:
260                 with open('debian/'+binaryName+'.postinst', 'w') as f:
261                         print >>f, "#!/bin/sh"
262                         print >>f, "set -e"
263                         print >>f, 'if [ "$1" = "configure" ]; then'
264                         for alternative in config.get('alternatives'):
265                                 alternative = shlex.split(alternative)
266                                 print >>f, safeCall('update-alternatives', '--install', alternative[0], alternative[1], alternative[2], alternative[3])
267                         print >>f, 'fi'
268                         print >>f, ''
269                         print >>f, '#DEBHELPER#'
270                         print >>f, ''
271                         print >>f, 'exit 0'
272                 with open('debian/'+binaryName+'.prerm', 'w') as f:
273                         print >>f, "#!/bin/sh"
274                         print >>f, "set -e"
275                         print >>f, 'if [ "$1" = "remove" ]; then'
276                         for alternative in config.get('alternatives'):
277                                 alternative = shlex.split(alternative)
278                                 print >>f, safeCall('update-alternatives', '--remove', alternative[1], alternative[2])
279                         print >>f, 'fi'
280                         print >>f, ''
281                         print >>f, '#DEBHELPER#'
282                         print >>f, ''
283                         print >>f, 'exit 0'
284         # rules file: build system specific
285         with open('debian/rules', 'w') as f:
286                 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
287                 r = buildSystem.ruleMaker(config)
288                 # global rules
289                 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
290                 if not dbgPackage:
291                         # disable debug information
292                         r.env["DEB_CFLAGS_APPEND"] = '-g0'
293                         r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
294                 r.dh += ['--parallel']
295                 if withPython2:
296                         r.dhWith.add('python2')
297                         r.rules['python2'] = ['dh_python2 --no-guessing-versions']
298                 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...)
299                 r.rules['auto_test'] = []
300                 # installation rule
301                 r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
302                 if 'binarySkipFiles' in config:
303                         r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " +
304                                 safeCall('rm', *config.get('binarySkipFiles')))
305                 # for debug packages
306                 if dbgPackage:
307                         r.rules['strip'] = [safeCall('dh_strip', '--dbg-package='+binaryName+"-dbg")] # put debug files in appropriate package
308                         r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)] # make the doc folder of the dbg package a symlink
309                 # wait after configuration?
310                 if config.getbool('waitAfterConfig', False):
311                         if not 'auto_configure' in r.rules: r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override
312                         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...
313                 # dump it to a file
314                 r.write(f)
315         mode = os.stat('debian/rules').st_mode
316         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
317         # return list of files that will be created
318         return files
319
320 def buildDebianPackage(config):
321         if not isinstance(config, ConfigDict):
322                 config = ConfigDict(config)
323         commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
324         command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
325         subprocess.check_call(commandInBuildEnv(config, command))
326         shutil.rmtree('debian') # it only contains what we just created
327
328 ###################################################################
329 # if we are called directly as script
330 if __name__ == "__main__":
331         try:
332                 # get config
333                 config = loadConfigFile('auto-debuild.conf')
334                 # generate debian files
335                 if os.path.exists('debian'):
336                         if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
337                                 sys.exit(1)
338                         shutil.rmtree('debian')
339                 files = createDebianFiles(config)
340                 # check if a file is overwritten
341                 for file in files:
342                         if os.path.exists(file):
343                                 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
344                                         sys.exit(1)
345                 # run compilation
346                 buildDebianPackage(config)
347                 # install files
348                 print "Installing created deb files..."
349                 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
350         except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
351                 print >> sys.stderr
352                 print >> sys.stderr
353                 if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
354                         print >> sys.stderr, "Interruped by user"
355                 else:
356                         print >> sys.stderr, "Error during package creation: %s" % str(e)
357                 print >> sys.stderr
358                 sys.exit(1)