ab04dc0e9d752e24d5aa2f8e918e457e3f1fb515
[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, "%:"
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         # "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
57         # also, we don't really support cross-building... ;-) (to do, we'd have to write shell code that checks whether BUILD_GNU_TYPE
58         #  and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
59         r = RulesFile()
60         r.dh += ["--buildsystem=autoconf"]
61         r.rules['auto_configure'] = [
62                 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
63                 'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
64                         './configure --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
65                         '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
66                         '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
67                         '--sysconfdir=/etc --localstatedir=/var '+
68                         safeCall(config.get('automakeParameters', []))
69         ]
70         r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration (no need for escaping here, obviously)
71         return r
72
73 # utility functions
74 def commandInBuildEnv(config, command):
75         schroot = config.get('schroot')
76         if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
77         return command
78
79 def getArchitecture(config):
80         cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
81         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
82         res = p.communicate()[0] # get only stdout
83         if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
84         return res[0:len(res)-1] # chop of the \n at the end
85
86 def writeDependency(f, name, list):
87         if len(list):
88                 print >>f, name+": "+', '.join(list)
89
90 # actual work functions
91 def createDebianFiles(config):
92         sourceName = config['sourceName']
93         binaryName = config.get('binaryName', sourceName+'-local')
94         name = config.get('name', os.getlogin())
95         email = config.get('email', os.getlogin()+'@'+os.uname()[1]) # user@hostname
96         debDir = os.path.expanduser(config['debDir'])
97         buildSystem = config['buildSystem']
98         version = config['version']
99         dbgPackage = config.get('dbgPackage', False)
100         parallelJobs = int(config.get('parallelJobs', 2))
101         packageArchitecture = config.get('architecture', 'any')
102         # we return the list of files generated, so we need to know the architecture
103         arch = getArchitecture(config)
104         files = []
105         # create folders
106         if os.path.exists('debian'): raise Exception('debian folder already exists?')
107         os.mkdir('debian')
108         os.mkdir('debian/source')
109         if not os.path.exists(debDir): os.mkdir(debDir)
110         # source format file
111         with open('debian/source/format', 'w') as f:
112                 print >>f, "3.0 (native)"
113         # compat file
114         with open('debian/compat', 'w') as f:
115                 print >>f, "9"
116         # copyright file
117         with open('debian/copyright', 'w') as f:
118                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
119         # changelog file
120         with open('debian/changelog', 'w') as f:
121                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
122                 print >>f, ""
123                 print >>f, "  * Auto-generated by auto-debuild"
124                 print >>f, ""
125                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
126         # control file
127         with open('debian/control', 'w') as f:
128                 print >>f, "Source:",sourceName
129                 print >>f, "Section:",config.get('section', 'misc')
130                 print >>f, "Priority: extra"
131                 print >>f, "Maintainer: %s <%s>" % (name, email)
132                 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + config.get('buildDepends', []))
133                 print >>f, "Standards-Version: 3.9.3"
134                 print >>f, ""
135                 print >>f, "Package:",binaryName
136                 print >>f, "Architecture:",packageArchitecture
137                 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
138                 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + config.get('binaryDepends', []))
139                 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
140                 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
141                 print >>f, "Description:",sourceName,"(auto-debuild)"
142                 print >>f, " Package auto-generated by auto-debuild."
143                 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
144                 if dbgPackage:
145                         print >>f, ""
146                         print >>f, "Package:",binaryName+"-dbg"
147                         print >>f, "Architecture:",packageArchitecture
148                         writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
149                         print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
150                         print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
151                         files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
152         # install file
153         with open('debian/'+binaryName+'.install', 'w') as f:
154                 for line in config.get('binaryInstallFiles', []):
155                         if line.startswith('/'): # a file from within the package, not from the source tree
156                                 line = 'debian/'+binaryName+line
157                         print >>f, line
158         # rules file: build system specific
159         with open('debian/rules', 'w') as f:
160                 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
161                 if buildSystem == 'cmake':
162                         r = cmakeRules(config)
163                 elif buildSystem == 'automake':
164                         r = automakeRules(config)
165                 else:
166                         raise Exception("Invalid build system "+buildSystem)
167                 # global rules
168                 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
169                 if not dbgPackage:
170                         # disable debug information
171                         r.env["DEB_CFLAGS_APPEND"] = '-g0'
172                         r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
173                 r.dh += ['--parallel']
174                 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...)
175                 r.rules['auto_test'] = []
176                 # installation rule
177                 r.rules['auto_install'] = [safeCall(['dh_auto_install', '--destdir=debian/'+binaryName])] # install everything into the binary package
178                 if 'binarySkipFiles' in config:
179                         r.rules['auto_install'].append(safeCall(['cd', 'debian/'+binaryName]) + " && " +
180                                 safeCall(['rm'] + config['binarySkipFiles']))
181                 # for debug packages
182                 if dbgPackage:
183                         r.rules['strip'] = [safeCall(['dh_strip', '--dbg-package='+binaryName+"-dbg"])] # put debug files in appropriate package
184                         r.rules['installdocs'] = [safeCall(['dh_installdocs', '--link-doc='+binaryName])] # make the doc folder of the dbg package a symlink
185                 # dump it to a file
186                 r.write(f)
187         mode = os.stat('debian/rules').st_mode
188         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
189         # return list of files that will be created
190         return files
191
192 def buildDebianPackage(config):
193         commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
194         command = ['nice', 'bash', '-c', ' && '.join(commands)]
195         subprocess.check_call(commandInBuildEnv(config, command))
196         shutil.rmtree('debian') # it only contains what we just created
197
198 ###################################################################
199 # if we are called directly as script
200 if __name__ == "__main__":
201         import imp
202         # get config
203         config = imp.load_source('config', 'auto-debuild.conf').__dict__
204         os.remove('auto-debuild.confc')
205         # generate debian files
206         if os.path.exists('debian'):
207                 if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
208                         sys.exit(1)
209                 shutil.rmtree('debian')
210         files = createDebianFiles(config)
211         # check if a file is overwritten
212         for file in files:
213                 if os.path.exists(file):
214                         if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
215                                 sys.exit(1)
216         # run compilation
217         buildDebianPackage(config)
218         # install files
219         print "Installing created deb files..."
220         subprocess.check_call(['sudo', 'dpkg', '--install'] + files)