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