add a function for configuration-building-installation
[auto-debuild.git] / auto_debuild.py
1 #!/usr/bin/python
2 import os, stat, time, subprocess, sys
3 from collections import OrderedDict
4
5 # abstract representation of rules file
6 class RulesFile:
7         def __init__(self):
8                 self.env = []
9                 self.dh = []
10                 self.rules = OrderedDict()
11         
12         def write(self, f):
13                 print >>f, "#!/usr/bin/make -f"
14                 print >>f, ""
15                 print >>f, "%:"
16                 print >>f, '\t'+' '.join(self.env)+' dh $@',' '.join(self.dh)
17                 for rule in self.rules:
18                         print >>f, ""
19                         print >>f, "override_dh_"+rule+":"
20                         for line in self.rules[rule]:
21                                 print >>f, "\t"+line
22
23 # build-system specific part of rules file
24 def cmakeRules(config):
25         r = RulesFile()
26         r.dh += ["--buildsystem=cmake", "--builddirectory=build.dir"] # dh parameters: "build" is not a good idea, as that's also the name of a target...
27         r.rules['auto_configure'] = [
28                 'mkdir -p build.dir',
29                 "cd build.dir && cmake .. -DCMAKE_INSTALL_PREFIX=/usr "+' '.join(config.get('cmakeParameters', []))
30         ]
31         r.rules['auto_clean'] = ['rm -f build.dir/CMakeCache.txt'] # clean old cmake cache
32         return r
33
34 def automakeRules(config):
35         r = RulesFile()
36         r.dh += ["--buildsystem=autoconf"]
37         r.rules['auto_configure'] = [
38                 'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
39                 'MULTIARCH=$$(dpkg-architecture -qDEB_BUILD_MULTIARCH) && '+
40                         './configure --build=$$BUILD_TYPE ' +
41                         '--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info ' +
42                         '--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
43                         '--sysconfdir=/etc --localstatedir=/var ' +
44                         ' '.join(config.get('automakeParameters', []))
45         ]
46         r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration
47         return r
48
49 # utility functions
50 def commandInBuildEnv(config, command):
51         schroot = config.get('schroot')
52         if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
53         return command
54
55 def getArchitecture(config):
56         cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_BUILD_ARCH'])
57         p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
58         res = p.communicate()[0] # get only stdout
59         if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
60         return res[0:len(res)-1] # chop of the \n at the end
61
62 def writeDebList(list):
63         return ', '.join(list)
64
65 # actual work functions
66 def createDebianFiles(config):
67         sourceName = config['sourceName']
68         binaryName = config.get('binaryName', sourceName+'-local')
69         name = config.get('name', os.getlogin())
70         email = config.get('email', os.getlogin()+'@'+os.uname()[1]) # user@hostname
71         debDir = os.path.expanduser(config['debDir'])
72         buildSystem = config['buildSystem']
73         version = config['version']
74         dbgPackage = config.get('dbgPackage', False)
75         packageArchitecture = config.get('architecture', 'any')
76         # we return the list of files generated, so we need to know the architecture
77         arch = getArchitecture(config)
78         files = []
79         # source format file
80         if not os.path.exists('debian/source'): os.mkdir('debian/source')
81         with open('debian/source/format', 'w') as f:
82                 print >>f, "3.0 (native)"
83         # compat file
84         with open('debian/compat', 'w') as f:
85                 print >>f, "9"
86         # copyright file
87         with open('debian/copyright', 'w') as f:
88                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
89         # changelog file
90         with open('debian/changelog', 'w') as f:
91                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
92                 print >>f, ""
93                 print >>f, "  * Auto-generated by auto-debuild"
94                 print >>f, ""
95                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
96         # control file
97         with open('debian/control', 'w') as f:
98                 print >>f, "Source:",sourceName
99                 print >>f, "Section:",config.get('section', 'misc')
100                 print >>f, "Priority: extra"
101                 print >>f, "Maintainer: %s <%s>" % (name, email)
102                 print >>f, "Build-Depends:",writeDebList(["debhelper (>= 9)"] + config.get('buildDepends', []))
103                 print >>f, "Standards-Version: 3.9.3"
104                 print >>f, ""
105                 print >>f, "Package:",binaryName
106                 print >>f, "Architecture:",packageArchitecture
107                 if 'binaryPreDepends' in config:
108                         print >>f, "Pre-Depends:",writeDebList(config['binaryPreDepends'])
109                 print >>f, "Depends:",writeDebList(["${shlibs:Depends}", "${misc:Depends}"] + config.get('binaryDepends', []))
110                 print >>f, "Provides:",writeDebList(config.get('binaryProvides', [sourceName]))
111                 print >>f, "Description:",sourceName,"(auto-debuild)"
112                 print >>f, " Package auto-generated by auto-debuild."
113                 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
114                 if dbgPackage:
115                         print >>f, ""
116                         print >>f, "Package:",binaryName+"-dbg"
117                         print >>f, "Architecture:",packageArchitecture
118                         print >>f, "Depends:",writeDebList(["${misc:Depends}", binaryName+" (= ${binary:Version})"])
119                         print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
120                         print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
121                         files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
122         # rules file: build system specific
123         with open('debian/rules', 'w') as f:
124                 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
125                 if buildSystem == 'cmake':
126                         r = cmakeRules(config)
127                 elif buildSystem == 'automake':
128                         r = automakeRules(config)
129                 else:
130                         raise Exception("Invalid build system "+buildSystem)
131                 # global rules
132                 r.env += ["DEB_BUILD_OPTIONS='parallel=2'"]
133                 if not dbgPackage: r.env += ["DEB_CFLAGS_APPEND='-g0'", "DEB_CXXFLAGS_APPEND='-g0'"] # disable debug information
134                 r.dh += ['--parallel']
135                 r.rules['builddeb'] = ['dh_builddeb --destdir='+debDir] # passing this gobally to dh results in weird problems (like stuff being installed there, and not in the package...)
136                 r.rules['auto_test'] = []
137                 r.rules['auto_install'] = ['dh_auto_install --destdir=debian/'+binaryName] # install everything into the binary package
138                 # for debug packages
139                 if dbgPackage:
140                         r.rules['strip'] = ['dh_strip --dbg-package='+binaryName+"-dbg"] # put debug files in appropriate package
141                         r.rules['installdocs'] = ['dh_installdocs --link-doc='+binaryName] # make the doc folder of the dbg package a symlink
142                 # dump it to a file
143                 r.write(f)
144         mode = os.stat('debian/rules').st_mode
145         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
146         # return list of files affected
147         return files
148
149 def buildDebianPackage(config):
150         commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
151         command = ['bash', '-c', ' && '.join(commands)]
152         subprocess.check_call(commandInBuildEnv(config, command))
153
154 # all at once
155 def createAndInstall(config, overwriteCheck = False):
156         # generate debian files
157         files = createDebianFiles(config)
158         # check if a file is overwritten
159         if overwriteCheck:
160                 for file in files:
161                         if os.path.exists(file):
162                                 if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
163                                         sys.exit(1)
164         # run compilation
165         buildDebianPackage(config)
166         # install files
167         subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
168
169 # if we are called directly as script
170 if __name__ == "__main__":
171         # get config
172         import imp
173         config = imp.load_source('config', 'debian/auto-debuild.conf').__dict__
174         os.remove('debian/auto-debuild.confc')
175         # and go for it
176         createAndInstall(config, overwriteCheck=True)