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 ' +
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 ' '.join(config.get('automakeParameters', []))
67 r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration
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 packageArchitecture = config.get('architecture', 'any')
98 # we return the list of files generated, so we need to know the architecture
99 arch = getArchitecture(config)
102 if not os.path.exists('debian'): os.mkdir('debian')
103 if not os.path.exists('debian/source'): os.mkdir('debian/source')
104 if not os.path.exists(debDir): os.mkdir(debDir)
106 with open('debian/source/format', 'w') as f:
107 print >>f, "3.0 (native)"
109 with open('debian/compat', 'w') as f:
112 with open('debian/copyright', 'w') as f:
113 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
115 with open('debian/changelog', 'w') as f:
116 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
118 print >>f, " * Auto-generated by auto-debuild"
120 print >>f, " --",name,"<"+email+"> "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
122 with open('debian/control', 'w') as f:
123 print >>f, "Source:",sourceName
124 print >>f, "Section:",config.get('section', 'misc')
125 print >>f, "Priority: extra"
126 print >>f, "Maintainer: %s <%s>" % (name, email)
127 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + config.get('buildDepends', []))
128 print >>f, "Standards-Version: 3.9.3"
130 print >>f, "Package:",binaryName
131 print >>f, "Architecture:",packageArchitecture
132 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
133 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + config.get('binaryDepends', []))
134 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
135 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
136 print >>f, "Description:",sourceName,"(auto-debuild)"
137 print >>f, " Package auto-generated by auto-debuild."
138 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
141 print >>f, "Package:",binaryName+"-dbg"
142 print >>f, "Architecture:",packageArchitecture
143 writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
144 print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
145 print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
146 files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
147 # rules file: build system specific
148 with open('debian/rules', 'w') as f:
149 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
150 if buildSystem == 'cmake':
151 r = cmakeRules(config)
152 elif buildSystem == 'automake':
153 r = automakeRules(config)
155 raise Exception("Invalid build system "+buildSystem)
157 r.env["DEB_BUILD_OPTIONS"] = 'parallel=2'
159 # disable debug information
160 r.env["DEB_CFLAGS_APPEND"] = '-g0'
161 r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
162 r.dh += ['--parallel']
163 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...)
164 r.rules['auto_test'] = []
165 r.rules['auto_install'] = [safeCall(['dh_auto_install', '--destdir=debian/'+binaryName])] # install everything into the binary package
168 r.rules['strip'] = ['dh_strip --dbg-package='+binaryName+"-dbg"] # put debug files in appropriate package
169 r.rules['installdocs'] = ['dh_installdocs --link-doc='+binaryName] # make the doc folder of the dbg package a symlink
172 mode = os.stat('debian/rules').st_mode
173 os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
174 # return list of files affected
177 def buildDebianPackage(config):
178 commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
179 command = ['nice', 'bash', '-c', ' && '.join(commands)]
180 subprocess.check_call(commandInBuildEnv(config, command))
183 def createAndInstall(config, overwriteCheck = False):
184 # generate debian files
185 files = createDebianFiles(config)
186 # check if a file is overwritten
189 if os.path.exists(file):
190 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
193 buildDebianPackage(config)
195 print "Installing created deb files..."
196 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
198 # if we are called directly as script
199 if __name__ == "__main__":
202 config = imp.load_source('config', 'debian/auto-debuild.conf').__dict__
203 os.remove('debian/auto-debuild.confc')
205 createAndInstall(config, overwriteCheck=True)