Support copying already installed files to another location
[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         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 os.path.exists('debian'): raise Exception('debian folder already exists?')
104         os.mkdir('debian')
105         os.mkdir('debian/source')
106         if not os.path.exists(debDir): os.mkdir(debDir)
107         # source format file
108         with open('debian/source/format', 'w') as f:
109                 print >>f, "3.0 (native)"
110         # compat file
111         with open('debian/compat', 'w') as f:
112                 print >>f, "9"
113         # copyright file
114         with open('debian/copyright', 'w') as f:
115                 print >>f, "Auto-generated by auto-debuild, not suited for distribution"
116         # changelog file
117         with open('debian/changelog', 'w') as f:
118                 print >>f, sourceName,"("+version+")","UNRELEASED; urgency=low"
119                 print >>f, ""
120                 print >>f, "  * Auto-generated by auto-debuild"
121                 print >>f, ""
122                 print >>f, " --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z')
123         # control file
124         with open('debian/control', 'w') as f:
125                 print >>f, "Source:",sourceName
126                 print >>f, "Section:",config.get('section', 'misc')
127                 print >>f, "Priority: extra"
128                 print >>f, "Maintainer: %s <%s>" % (name, email)
129                 writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + config.get('buildDepends', []))
130                 print >>f, "Standards-Version: 3.9.3"
131                 print >>f, ""
132                 print >>f, "Package:",binaryName
133                 print >>f, "Architecture:",packageArchitecture
134                 writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
135                 writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + config.get('binaryDepends', []))
136                 writeDependency(f, "Recommends", config.get('binaryRecommends', []))
137                 writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
138                 print >>f, "Description:",sourceName,"(auto-debuild)"
139                 print >>f, " Package auto-generated by auto-debuild."
140                 files.append(os.path.join(debDir, "%s_%s_%s.deb" % (binaryName, version, arch)))
141                 if dbgPackage:
142                         print >>f, ""
143                         print >>f, "Package:",binaryName+"-dbg"
144                         print >>f, "Architecture:",packageArchitecture
145                         writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
146                         print >>f, "Description:",sourceName,"debug smbols (auto-debuild)"
147                         print >>f, " Package containing debug symbols for "+sourceName+", auto-generated by auto-debuild."
148                         files.append(os.path.join(debDir, "%s-dbg_%s_%s.deb" % (binaryName, version, arch)))
149         # install file
150         with open('debian/'+binaryName+'.install', 'w') as f:
151                 for line in config.get('binaryInstall', []):
152                         if line.startswith('/'): # a file from within the package, not from the source tree
153                                 line = 'debian/'+binaryName+line
154                         print >>f, line
155         # rules file: build system specific
156         with open('debian/rules', 'w') as f:
157                 # get rule file for build system: may only touch auto_config and auto_clean rules and the dh options
158                 if buildSystem == 'cmake':
159                         r = cmakeRules(config)
160                 elif buildSystem == 'automake':
161                         r = automakeRules(config)
162                 else:
163                         raise Exception("Invalid build system "+buildSystem)
164                 # global rules
165                 r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
166                 if not dbgPackage:
167                         # disable debug information
168                         r.env["DEB_CFLAGS_APPEND"] = '-g0'
169                         r.env["DEB_CXXFLAGS_APPEND"] = '-g0'
170                 r.dh += ['--parallel']
171                 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...)
172                 r.rules['auto_test'] = []
173                 # installation rule
174                 r.rules['auto_install'] = [safeCall(['dh_auto_install', '--destdir=debian/'+binaryName])] # install everything into the binary package
175                 if 'binarySkipFiles' in config:
176                         r.rules['auto_install'].append(safeCall(['cd', 'debian/'+binaryName]) + " && " +
177                                 safeCall(['rm'] + config['binarySkipFiles']))
178                 # for debug packages
179                 if dbgPackage:
180                         r.rules['strip'] = [safeCall(['dh_strip', '--dbg-package='+binaryName+"-dbg"])] # put debug files in appropriate package
181                         r.rules['installdocs'] = [safeCall(['dh_installdocs', '--link-doc='+binaryName])] # make the doc folder of the dbg package a symlink
182                 # dump it to a file
183                 r.write(f)
184         mode = os.stat('debian/rules').st_mode
185         os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
186         # return list of files that will be created
187         return files
188
189 def buildDebianPackage(config):
190         commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary', 'debian/rules clean']
191         command = ['nice', 'bash', '-c', ' && '.join(commands)]
192         subprocess.check_call(commandInBuildEnv(config, command))
193         shutil.rmtree('debian') # it only contains what we just created
194
195 ###################################################################
196 # if we are called directly as script
197 if __name__ == "__main__":
198         import imp
199         # get config
200         config = imp.load_source('config', 'auto-debuild.conf').__dict__
201         os.remove('auto-debuild.confc')
202         # generate debian files
203         if os.path.exists('debian'):
204                 if raw_input("A debian folder already exists, to you want to remove it (y/N)? ").lower() != "y":
205                         sys.exit(1)
206                 shutil.rmtree('debian')
207         files = createDebianFiles(config)
208         # check if a file is overwritten
209         for file in files:
210                 if os.path.exists(file):
211                         if raw_input("Do you want to overwrite %s (y/N)? " % file).lower() != "y":
212                                 sys.exit(1)
213         # run compilation
214         buildDebianPackage(config)
215         # install files
216         print "Installing created deb files..."
217         subprocess.check_call(['sudo', 'dpkg', '--install'] + files)