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