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