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