add support for automake-based programs
[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                 './configure --build=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) --prefix=/usr --sysconfdir=/etc --localstatedir=/var ' +
39                         ' '.join(config.get('automakeParameters', []))
40         ]
41         r.rules['auto_clean'] = ['rm -f config.status'] # do not re-use old configuration
42         return r
43
44 # utility functions
45 def getArchitecture():
46         p = subprocess.Popen(['dpkg-architecture', '-qDEB_BUILD_ARCH'], stdout=subprocess.PIPE)
47         res = p.communicate()[0] # get only stdout
48         if p.returncode != 0: raise Exception("Querying dpkg for the architecture failed")
49         return res[0:len(res)-1] # chop of the \n at the end
50
51 def writeDebList(list):
52         return ', '.join(list)
53
54 # actual work functions
55 def createDebianFiles(config):
56         sourceName = config['sourceName']
57         binaryName = config.get('binaryName', sourceName+'-local')
58         name = config.get('name', os.getlogin())
59         email = config.get('email', os.getlogin()+'@'+os.uname()[1]) # user@hostname
60         debDir = os.path.expanduser(config['debDir'])
61         buildSystem = config['buildSystem']
62         version = config['version']
63         dbgPackage = config.get('dbgPackage', False)
64         packageArchitecture = config.get('architecture', 'any')
65         # we return the list of files generated
66         arch = getArchitecture()
67         files = []
68         # source format file
69         if not os.path.exists('debian/source'): os.mkdir('debian/source')
70         with open('debian/source/format', 'w') as f:
71                 print >>f, "3.0 (native)"
72         # compat file
73         with open('debian/compat', 'w') as f:
74                 print >>f, "9"
75         # copyright file
76         with open('debian/copyright', 'w') as f:
77                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
78         # changelog file
79         with open('debian/changelog', 'w') as f:
80                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
81                 print >>f, ""
82                 print >>f, "  * Auto-generated by auto-debuild"
83                 print >>f, ""
84                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
85         # control file
86         with open('debian/control', 'w') as f:
87                 print >>f, "Source:",sourceName
88                 print >>f, "Section:",config.get('section', 'misc')
89                 print >>f, "Priority: extra"
90                 print >>f, "Maintainer: %s <%s>" % (name, email)
91                 print >>f, "Build-Depends:",writeDebList(["debhelper (>= 9)"] + config.get('buildDepends', []))
92                 print >>f, "Standards-Version: 3.9.3"
93                 print >>f, ""
94                 print >>f, "Package:",binaryName
95                 print >>f, "Architecture:",packageArchitecture
96                 print >>f, "Depends:",writeDebList(["${shlibs:Depends}", "${misc:Depends}"] + config.get('binaryDepends', []))
97                 print >>f, "Provides:",writeDebList(config.get('binaryProvides', [sourceName]))
98                 print >>f, "Description:",sourceName,"(auto-debuild)"
99                 print >>f, " Package auto-generated by auto-debuild."
100                 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
101                 if dbgPackage:
102                         print >>f, ""
103                         print >>f, "Package:",binaryName+"-dbg"
104                         print >>f, "Architecture:",packageArchitecture
105                         print >>f, "Depends:",writeDebList(["${misc:Depends}", binaryName+" (= ${binary:Version})"])
106                         print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
107                         print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
108                         files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
109         # rules file: build system specific
110         with open('debian/rules', 'w') as f:
111                 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
112                 if buildSystem == 'cmake':
113                         r = cmakeRules(config)
114                 elif buildSystem == 'automake':
115                         r = automakeRules(config)
116                 else:
117                         raise Exception("Invalid build system "+buildSystem)
118                 # global rules
119                 r.env += ["DEB_BUILD_OPTIONS='parallel=2'"]
120                 if not dbgPackage: r.env += ["DEB_CFLAGS_APPEND='-g0'", "DEB_CXXFLAGS_APPEND='-g0'"] # disable debug information
121                 r.dh += ['--parallel']
122                 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...)
123                 r.rules['auto_test'] = []
124                 r.rules['auto_install'] = ['dh_auto_install --destdir=debian/'+binaryName] # install everything into the binary package
125                 # for debug packages
126                 if dbgPackage:
127                         r.rules['strip'] = ['dh_strip --dbg-package='+binaryName+"-dbg"]
128                         r.rules['installdocs'] = ['dh_installdocs --link-doc='+binaryName]
129                 # dump it to a file
130                 r.write(f)
131         mode = os.stat('debian/rules').st_mode
132         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
133         # return list of files affected
134         return files
135
136 def buildDebianPackage():
137         subprocess.check_call(['dpkg-checkbuilddeps'])
138         subprocess.check_call(['debian/rules', 'clean'])
139         subprocess.check_call(['debian/rules', 'build'])
140         subprocess.check_call(['fakeroot', 'debian/rules', 'binary'])
141         subprocess.check_call(['debian/rules', 'clean'])
142
143 # if we are called directly as script
144 if __name__ == "__main__":
145         # generate debian files
146         import imp
147         config = imp.load_source('config', 'debian/auto-debuild.conf')
148         os.remove('debian/auto-debuild.confc')
149         files = createDebianFiles(config.__dict__)
150         # check if a file is overwritten
151         for file in files:
152                 if os.path.exists(file):
153                         if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
154                                 sys.exit(1)
155         # run compilation
156         buildDebianPackage()
157         # install files
158         subprocess.check_call(['sudo', 'dpkg', '--install'] + files)