9252652ad246fd82a0c830d0f6f0c0374fcd0051
[auto-debuild.git] / auto_debuild.py
1 #!/usr/bin/python
2 import os, 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, "%:"
34                 print >>f, '\t'+self.env2str()+' dh $@ '+safeCall(self.dh)
35                 for rule in self.rules:
36                         print >>f, ""
37                         print >>f, "override_dh_"+rule+":"
38                         for line in self.rules[rule]:
39                                 print >>f, "\t"+line
40
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...
44         srcDir = os.getcwd()
45         r = RulesFile()
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', []))
51         ]
52         r.rules['auto_clean'] = [safeCall(['rm', '-f', os.path.join(buildDir, 'CMakeCache.txt')])] # clean old cmake cache
53         return r
54
55 def automakeRules(config):
56         r = RulesFile()
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', []))
66         ]
67         r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
68         return r
69
70 # utility functions
71 def commandInBuildEnv(config, command):
72         schroot = config.get('schroot')
73         if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
74         return command
75
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
82
83 def writeDependency(f, name, list):
84         if len(list):
85                 print >>f, name+": "+', '.join(list)
86
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)
100         files = []
101         # create folders
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)
105         # source format file
106         with open('debian/source/format', 'w') as f:
107                 print >>f, "3.0 (native)"
108         # compat file
109         with open('debian/compat', 'w') as f:
110                 print >>f, "9"
111         # copyright file
112         with open('debian/copyright', 'w') as f:
113                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
114         # changelog file
115         with open('debian/changelog', 'w') as f:
116                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
117                 print >>f, ""
118                 print >>f, "  * Auto-generated by auto-debuild"
119                 print >>f, ""
120                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
121         # control file
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"
129                 print >>f, ""
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)))
139                 if dbgPackage:
140                         print >>f, ""
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)
154                 else:
155                         raise Exception("Invalid build system "+buildSystem)
156                 # global rules
157                 r.env["DEB_BUILD_OPTIONS"] = 'parallel=2'
158                 if not dbgPackage:
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
166                 # for debug packages
167                 if dbgPackage:
168                         r.rules['strip'] = [safeCall(['dh_strip', '--dbg-package='+binaryName+"-dbg"])] # put debug files in appropriate package
169                         r.rules['installdocs'] = [safeCall(['dh_installdocs', '--link-doc='+binaryName])] # make the doc folder of the dbg package a symlink
170                 # dump it to a file
171                 r.write(f)
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
175         return files
176
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))
181
182 # all at once
183 def createAndInstall(config, overwriteCheck = False):
184         # generate debian files
185         files = createDebianFiles(config)
186         # check if a file is overwritten
187         if overwriteCheck:
188                 for file in files:
189                         if os.path.exists(file):
190                                 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
191                                         sys.exit(1)
192         # run compilation
193         buildDebianPackage(config)
194         # install files
195         print "Installing created deb files..."
196         subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
197
198 # if we are called directly as script
199 if __name__ == "__main__":
200         # get config
201         import imp
202         config = imp.load_source('config', 'debian/auto-debuild.conf').__dict__
203         os.remove('debian/auto-debuild.confc')
204         # and go for it
205         createAndInstall(config, overwriteCheck=True)