90d616dbe7bffc29ab26f8ab85c5d70fc05b0196
[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         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)
101         files = []
102         # create folders
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)
106         # source format file
107         with open('debian/source/format', 'w') as f:
108                 print >>f, "3.0 (native)"
109         # compat file
110         with open('debian/compat', 'w') as f:
111                 print >>f, "9"
112         # copyright file
113         with open('debian/copyright', 'w') as f:
114                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
115         # changelog file
116         with open('debian/changelog', 'w') as f:
117                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
118                 print >>f, ""
119                 print >>f, "  * Auto-generated by auto-debuild"
120                 print >>f, ""
121                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
122         # control file
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"
130                 print >>f, ""
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)))
140                 if dbgPackage:
141                         print >>f, ""
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)
155                 else:
156                         raise Exception("Invalid build system "+buildSystem)
157                 # global rules
158                 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
159                 if not dbgPackage:
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'] = []
166                 # installation rule
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']))
171                 # for debug packages
172                 if dbgPackage:
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
175                 # dump it to a file
176                 r.write(f)
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
180         return files
181
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))
186
187 # all at once
188 def createAndInstall(config, overwriteCheck = False):
189         # generate debian files
190         files = createDebianFiles(config)
191         # check if a file is overwritten
192         if overwriteCheck:
193                 for file in files:
194                         if os.path.exists(file):
195                                 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
196                                         sys.exit(1)
197         # run compilation
198         buildDebianPackage(config)
199         # install files
200         print "Installing created deb files..."
201         subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
202
203 # if we are called directly as script
204 if __name__ == "__main__":
205         # get config
206         import imp
207         config = imp.load_source('config', 'debian/auto-debuild.conf').__dict__
208         os.remove('debian/auto-debuild.confc')
209         # and go for it
210         createAndInstall(config, overwriteCheck=True)