2 import os, stat, time, subprocess, sys
3 from collections import OrderedDict
5 # some utility functions
9 assert arg.find("'") < 0 # ' is not supported
10 if len(res): res += " "
14 # abstract representation of rules file
19 self.rules = OrderedDict()
23 for name in self.env: # we rely on the name being sane (i.e., no special characters)
25 assert val.find("'") < 0 # ' is not supported
26 if len(res): res += " "
27 res += name+"='"+val+"'"
31 print >>f, "#!/usr/bin/make -f"
34 print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(self.dh)
35 for rule in self.rules:
37 print >>f, "override_dh_"+rule+":"
38 for line in self.rules[rule]:
41 # build-system specific part of rules file
42 def cmakeRules(config):
43 buildDir = config.get('buildDir', 'build.dir') # "build" is not a good idea, as that's also the name of a target...
46 r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
47 r.rules['auto_configure'] = [
48 safeCall(["mkdir", "-p", buildDir]),
49 safeCall(["cd", buildDir]) + " && " +
50 safeCall(["cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr"] + config.get('cmakeParameters', []))
52 r.rules['auto_clean'] = [safeCall(['rm', '-f', os.path.join(buildDir, 'CMakeCache.txt')])] # clean old cmake cache
55 def automakeRules(config):
57 r.dh += ["--buildsystem=autoconf"]
58 r.rules['auto_configure'] = [
59 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
60 'MULTIARCH=$$(dpkg-architecture -qDEB_BUILD_MULTIARCH) && '+
61 './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
62 '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
63 '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
64 '--sysconfdir=/etc --localstatedir=/var '+
65 safeCall(config.get('automakeParameters', []))
67 r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
71 def commandInBuildEnv(config, command):
72 schroot = config.get('schroot')
73 if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
76 def getArchitecture(config):
77 cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_BUILD_ARCH'])
78 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
79 res = p.communicate()[0] # get only stdout
80 if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
81 return res[0:len(res)-1] # chop of the \n at the end
83 def writeDependency(f, name, list):
85 print >>f, name+": "+', '.join(list)
87 # actual work functions
88 def createDebianFiles(config):
89 sourceName = config['sourceName']
90 binaryName = config.get('binaryName', sourceName+'-local')
91 name = config.get('name', os.getlogin())
92 email = config.get('email', os.getlogin()+'@'+os.uname()[1]) # user@hostname
93 debDir = os.path.expanduser(config['debDir'])
94 buildSystem = config['buildSystem']
95 version = config['version']
96 dbgPackage = config.get('dbgPackage', False)
97 parallelJobs = int(config.get('parallelJobs', 2))
98 packageArchitecture = config.get('architecture', 'any')
99 # we return the list of files generated, so we need to know the architecture
100 arch = getArchitecture(config)
103 if not os.path.exists('debian'): os.mkdir('debian')
104 if not os.path.exists('debian/source'): os.mkdir('debian/source')
105 if not os.path.exists(debDir): os.mkdir(debDir)
107 with open('debian/source/format', 'w') as f:
108 print >>f, "3.0 (native)"
110 with open('debian/compat', 'w') as f:
113 with open('debian/copyright', 'w') as f:
114 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
116 with open('debian/changelog', 'w') as f:
117 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
119 print >>f, " * Auto-generated by auto-debuild"
121 print >>f, " --",name,"<"+email+"> "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
123 with open('debian/control', 'w') as f:
124 print >>f, "Source:",sourceName
125 print >>f, "Section:",config.get('section', 'misc')
126 print >>f, "Priority: extra"
127 print >>f, "Maintainer: %s <%s>" % (name, email)
128 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + config.get('buildDepends', []))
129 print >>f, "Standards-Version: 3.9.3"
131 print >>f, "Package:",binaryName
132 print >>f, "Architecture:",packageArchitecture
133 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
134 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + config.get('binaryDepends', []))
135 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
136 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
137 print >>f, "Description:",sourceName,"(auto-debuild)"
138 print >>f, " Package auto-generated by auto-debuild."
139 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
142 print >>f, "Package:",binaryName+"-dbg"
143 print >>f, "Architecture:",packageArchitecture
144 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
145 print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
146 print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
147 files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
148 # rules file: build system specific
149 with open('debian/rules', 'w') as f:
150 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
151 if buildSystem == 'cmake':
152 r = cmakeRules(config)
153 elif buildSystem == 'automake':
154 r = automakeRules(config)
156 raise Exception("Invalid build system "+buildSystem)
158 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
160 # disable debug information
161 r.env["DEB_CFLAGS_APPEND"] = '-g0'
162 r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
163 r.dh += ['--parallel']
164 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...)
165 r.rules['auto_test'] = []
167 r.rules['auto_install'] = [safeCall(['dh_auto_install', '--destdir=debian/'+binaryName])] # install everything into the binary package
168 if 'binarySkipFiles' in config:
169 r.rules['auto_install'].append(safeCall(['cd', 'debian/'+binaryName]) + " && " +
170 safeCall(['rm'] + config['binarySkipFiles']))
173 r.rules['strip'] = [safeCall(['dh_strip', '--dbg-package='+binaryName+"-dbg"])] # put debug files in appropriate package
174 r.rules['installdocs'] = [safeCall(['dh_installdocs', '--link-doc='+binaryName])] # make the doc folder of the dbg package a symlink
177 mode = os.stat('debian/rules').st_mode
178 os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
179 # return list of files affected
182 def buildDebianPackage(config):
183 commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
184 command = ['nice', 'bash', '-c', ' && '.join(commands)]
185 subprocess.check_call(commandInBuildEnv(config, command))
188 def createAndInstall(config, overwriteCheck = False):
189 # generate debian files
190 files = createDebianFiles(config)
191 # check if a file is overwritten
194 if os.path.exists(file):
195 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
198 buildDebianPackage(config)
200 print "Installing created deb files..."
201 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
203 # if we are called directly as script
204 if __name__ == "__main__":
207 config = imp.load_source('config', 'debian/auto-debuild.conf').__dict__
208 os.remove('debian/auto-debuild.confc')
210 createAndInstall(config, overwriteCheck=True)