blob: 6e7cf8de9e92cb0ad08bc71e6885e5c676da2266 [file] [log] [blame]
Zhenkai Zhu9eec5822012-10-02 11:48:12 -07001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4#
5# Loosely based on original bash-version by Sebastian Schlingmann (based, again, on a OSX application bundler
6# by Thomas Keller).
7#
8
9import sys, os, string, re, shutil, plistlib, tempfile, exceptions, datetime, tarfile
10from subprocess import Popen, PIPE
11from optparse import OptionParser
12
Alexander Afanasyevba87ea32013-07-14 12:27:03 -070013import platform
14
15if platform.system () != 'Darwin':
16 print "This script is indended to be run only on OSX platform"
17 exit (1)
18
19SUPPORTED_VERSION = "10.7"
20BINARY_POSTFIX = "Lion-10.7"
21
22if '.'.join (platform.mac_ver()[0].split('.')[0:2]) != SUPPORTED_VERSION:
23 print "This script is indended to be run only on OSX %s platform" % SUPPORTED_VERSION
24 exit (1)
25
Zhenkai Zhu9eec5822012-10-02 11:48:12 -070026options = None
27
28def gitrev():
29 return os.popen('git describe').read()[:-1]
30
31def codesign(path):
32 '''Call the codesign executable.'''
33
34 if hasattr(path, 'isalpha'):
35 path = (path,)
36 for p in path:
37 p = Popen(('codesign', '--keychain', options.codesign_keychain, '--signature-size', '6400', '-vvvv', '-s', options.codesign, p))
38 retval = p.wait()
39 if retval != 0:
40 return retval
41 return 0
42
43class AppBundle(object):
44
Alexander Afanasyevba87ea32013-07-14 12:27:03 -070045 def __init__(self, bundle, version, binary):
46 shutil.copytree (src = binary, dst = bundle, symlinks = True)
47
48 self.framework_path = ''
49 self.handled_libs = {}
50 self.bundle = bundle
51 self.version = version
52 self.infopath = os.path.join(os.path.abspath(bundle), 'Contents', 'Info.plist')
53 self.infoplist = plistlib.readPlist(self.infopath)
54 self.binary = os.path.join(os.path.abspath(bundle), 'Contents', 'MacOS', self.infoplist['CFBundleExecutable'])
55 print ' * Preparing AppBundle'
56
Zhenkai Zhu9eec5822012-10-02 11:48:12 -070057 def is_system_lib(self, lib):
58 '''
59 Is the library a system library, meaning that we should not include it in our bundle?
60 '''
61 if lib.startswith('/System/Library/'):
62 return True
63 if lib.startswith('/usr/lib/'):
64 return True
65
66 return False
67
68 def is_dylib(self, lib):
69 '''
70 Is the library a dylib?
71 '''
72 return lib.endswith('.dylib')
73
74 def get_framework_base(self, fw):
75 '''
76 Extracts the base .framework bundle path from a library in an abitrary place in a framework.
77 '''
78 paths = fw.split('/')
79 for i, str in enumerate(paths):
80 if str.endswith('.framework'):
81 return '/'.join(paths[:i+1])
82 return None
83
84 def is_framework(self, lib):
85 '''
86 Is the library a framework?
87 '''
88 return bool(self.get_framework_base(lib))
89
90 def get_binary_libs(self, path):
91 '''
92 Get a list of libraries that we depend on.
93 '''
94 m = re.compile('^\t(.*)\ \(.*$')
95 libs = Popen(['otool', '-L', path], stdout=PIPE).communicate()[0]
96 libs = string.split(libs, '\n')
97 ret = []
98 bn = os.path.basename(path)
99 for line in libs:
100 g = m.match(line)
101 if g is not None:
102 lib = g.groups()[0]
103 if lib != bn:
104 ret.append(lib)
105 return ret
106
107 def handle_libs(self):
108 '''
109 Copy non-system libraries that we depend on into our bundle, and fix linker
110 paths so they are relative to our bundle.
111 '''
112 print ' * Taking care of libraries'
113
114 # Does our fwpath exist?
115 fwpath = os.path.join(os.path.abspath(self.bundle), 'Contents', 'Frameworks')
116 if not os.path.exists(fwpath):
117 os.mkdir(fwpath)
118
119 self.handle_binary_libs()
120
121 #actd = os.path.join(os.path.abspath(self.bundle), 'Contents', 'MacOS', 'actd')
122 #if os.path.exists(actd):
123 # self.handle_binary_libs(actd)
124
125 def handle_binary_libs(self, macho=None):
126 '''
127 Fix up dylib depends for a specific binary.
128 '''
129 print "macho is ", macho
130 # Does our fwpath exist already? If not, create it.
131 if not self.framework_path:
132 self.framework_path = self.bundle + '/Contents/Frameworks'
133 if not os.path.exists(self.framework_path):
134 os.mkdir(self.framework_path)
135 else:
136 shutil.rmtree(self.framework_path)
137 os.mkdir(self.framework_path)
138
139 # If we weren't explicitly told which binary to operate on, pick the
140 # bundle's default executable from its property list.
141 if macho is None:
142 macho = os.path.abspath(self.binary)
143 else:
144 macho = os.path.abspath(macho)
145
146 libs = self.get_binary_libs(macho)
147
148 for lib in libs:
149
150 # Skip system libraries
151 if self.is_system_lib(lib):
152 continue
153
154 # Frameworks are 'special'.
155 if self.is_framework(lib):
156 fw_path = self.get_framework_base(lib)
157 basename = os.path.basename(fw_path)
158 name = basename.split('.framework')[0]
159 rel = basename + '/' + name
160
161 abs = self.framework_path + '/' + rel
162
163 if not basename in self.handled_libs:
164 dst = self.framework_path + '/' + basename
165 shutil.copytree(fw_path, dst, symlinks=True)
166 if name.startswith('Qt'):
167 try:
168 os.remove(dst + '/Headers')
169 os.remove(dst + '/' + name + '.prl')
170 os.remove(dst + '/' + name + '_debug')
171 os.remove(dst + '/' + name + '_debug.prl')
172 shutil.rmtree(dst + '/Versions/4/Headers')
173 os.remove(dst + '/Versions/4/' + name + '_debug')
174 except OSError:
175 pass
176 os.chmod(abs, 0755)
177 os.system('install_name_tool -id @executable_path/../Frameworks/%s %s' % (rel, abs))
178 self.handled_libs[basename] = True
179 self.handle_binary_libs(abs)
180 os.chmod(macho, 0755)
181 os.system('install_name_tool -change %s @executable_path/../Frameworks/%s %s' % (lib, rel, macho))
182
183 # Regular dylibs
184 else:
185 basename = os.path.basename(lib)
186 rel = basename
187
188 if not basename in self.handled_libs:
189 print lib
190 print self.framework_path + '/' + basename
191 try:
192 shutil.copy(lib, self.framework_path + '/' + basename)
193 except IOError:
194 print "IOError!" + self.framework_path + '/' + basename + "does not exist\n"
195 continue
196
197 abs = self.framework_path + '/' + rel
198 os.chmod(abs, 0755)
199 os.system('install_name_tool -id @executable_path/../Frameworks/%s %s' % (rel, abs))
200 self.handled_libs[basename] = True
201 self.handle_binary_libs(abs)
202 os.chmod(macho, 0755)
203 os.system('install_name_tool -change %s @executable_path/../Frameworks/%s %s' % (lib, rel, macho))
204
205 def copy_resources(self, rsrcs):
206 '''
207 Copy needed resources into our bundle.
208 '''
209 print ' * Copying needed resources'
210 rsrcpath = os.path.join(self.bundle, 'Contents', 'Resources')
211 if not os.path.exists(rsrcpath):
212 os.mkdir(rsrcpath)
213
214 # Copy resources already in the bundle
215 for rsrc in rsrcs:
216 b = os.path.basename(rsrc)
217 if os.path.isdir(rsrc):
218 shutil.copytree(rsrc, os.path.join(rsrcpath, b), symlinks=True)
219 elif os.path.isfile(rsrc):
220 shutil.copy(rsrc, os.path.join(rsrcpath, b))
221
222 return
223
224 def copy_qt_plugins(self):
225 '''
226 Copy over any needed Qt plugins.
227 '''
228
229 print ' * Copying Qt and preparing plugins'
230
231 src = os.popen('qmake -query QT_INSTALL_PLUGINS').read().strip()
232 dst = os.path.join(self.bundle, 'Contents', 'QtPlugins')
233 shutil.copytree(src, dst, symlinks=False)
234
235 top = dst
236 files = {}
237
238 def cb(arg, dirname, fnames):
239 if dirname == top:
240 return
241 files[os.path.basename(dirname)] = fnames
242
243 os.path.walk(top, cb, None)
244
245 exclude = ( 'phonon_backend', 'designer', 'script' )
246
247 for dir, files in files.items():
248 absdir = dst + '/' + dir
249 if dir in exclude:
250 shutil.rmtree(absdir)
251 continue
252 for file in files:
253 abs = absdir + '/' + file
254 if file.endswith('_debug.dylib'):
255 os.remove(abs)
256 else:
257 os.system('install_name_tool -id %s %s' % (file, abs))
258 self.handle_binary_libs(abs)
259
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700260 def set_min_macosx_version(self, version):
261 '''
262 Set the minimum version of Mac OS X version that this App will run on.
263 '''
264 print ' * Setting minimum Mac OS X version to: %s' % (version)
265 self.infoplist['LSMinimumSystemVersion'] = version
266
267 def done(self):
268 plistlib.writePlist(self.infoplist, self.infopath)
269 print ' * Done!'
270 print ''
271
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700272class FolderObject(object):
273 class Exception(exceptions.Exception):
274 pass
275
276 def __init__(self):
277 self.tmp = tempfile.mkdtemp()
278
279 def copy(self, src, dst='/'):
280 '''
281 Copy a file or directory into foler
282 '''
283 asrc = os.path.abspath(src)
284
285 if dst[0] != '/':
286 raise self.Exception
287
288 # Determine destination
289 if dst[-1] == '/':
290 adst = os.path.abspath(self.tmp + '/' + dst + os.path.basename(src))
291 else:
292 adst = os.path.abspath(self.tmp + '/' + dst)
293
294 if os.path.isdir(asrc):
295 print ' * Copying directory: %s' % os.path.basename(asrc)
296 shutil.copytree(asrc, adst, symlinks=True)
297 elif os.path.isfile(asrc):
298 print ' * Copying file: %s' % os.path.basename(asrc)
299 shutil.copy(asrc, adst)
300
301 def symlink(self, src, dst):
302 '''
303 Create a symlink inside the folder
304 '''
305 asrc = os.path.abspath(src)
306 adst = self.tmp + '/' + dst
307 print " * Creating symlink %s" % os.path.basename(asrc)
308 os.symlink(asrc, adst)
309
310 def mkdir(self, name):
311 '''
312 Create a directory inside the folder.
313 '''
314 print ' * Creating directory %s' % os.path.basename(name)
315 adst = self.tmp + '/' + name
316 os.makedirs(adst)
317
318class DiskImage(FolderObject):
319
320 def __init__(self, filename, volname):
321 FolderObject.__init__(self)
322 print ' * Preparing to create diskimage'
323 self.filename = filename
324 self.volname = volname
325
326 def create(self):
327 '''
328 Create the disk image
329 '''
330 print ' * Creating disk image. Please wait...'
331 if os.path.exists(self.filename):
332 shutil.rmtree(self.filename)
333 p = Popen(['hdiutil', 'create',
334 '-srcfolder', self.tmp,
335 '-format', 'UDBZ',
336 '-volname', self.volname,
337 self.filename])
338
339 retval = p.wait()
340 print ' * Removing temporary directory.'
341 shutil.rmtree(self.tmp)
342 print ' * Done!'
343
344
345if __name__ == '__main__':
346 parser = OptionParser()
Alexander Afanasyevb4b92292013-07-09 13:54:59 -0700347 parser.add_option('-r', '--release', dest='release', help='Build a release. This determines the version number of the release.')
348 parser.add_option('-s', '--snapshot', dest='snapshot', help='Build a snapshot release. This determines the \'snapshot version\'.')
349 parser.add_option('-g', '--git', dest='git', help='Build a snapshot release. Use the git revision number as the \'snapshot version\'.', action='store_true', default=False)
350 parser.add_option('--codesign', dest='codesign', help='Identity to use for code signing. (If not set, no code signing will occur)')
351 parser.add_option('--codesign-keychain', dest='codesign_keychain', help='The keychain to use when invoking the codesign utility.')
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700352
353 options, args = parser.parse_args()
354
355 # Release
356 if options.release:
357 ver = options.release
358 # Snapshot
359 elif options.snapshot or options.git:
360 if not options.git:
361 ver = options.snapshot
362 else:
363 ver = gitrev()
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700364 else:
Alexander Afanasyevb4b92292013-07-09 13:54:59 -0700365 print 'ERROR: Neither snapshot or release selected. Bailing.'
366 parser.print_help ()
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700367 sys.exit(1)
368
369
370 # Do the finishing touches to our Application bundle before release
Alexander Afanasyevba87ea32013-07-14 12:27:03 -0700371 a = AppBundle('build/%s/ChronoChat.app' % (BINARY_POSTFIX), ver, 'build/ChronoChat.app')
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700372 a.copy_qt_plugins()
373 a.handle_libs()
Alexander Afanasyevb4b92292013-07-09 13:54:59 -0700374 a.copy_resources(['qt.conf'])
Alexander Afanasyevba87ea32013-07-14 12:27:03 -0700375 a.set_min_macosx_version('%s.0' % SUPPORTED_VERSION)
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700376 a.done()
377
378 # Sign our binaries, etc.
379 if options.codesign:
380 print ' * Signing binaries with identity `%s\'' % options.codesign
381 binaries = (
Alexander Afanasyevb4b92292013-07-09 13:54:59 -0700382 'build/ChronoChat.app',
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700383 )
384
385 codesign(binaries)
386 print ''
387
388 # Create diskimage
Alexander Afanasyevba87ea32013-07-14 12:27:03 -0700389 title = "ChronoChat-%s-%s" % (ver, BINARY_POSTFIX)
Alexander Afanasyevb4b92292013-07-09 13:54:59 -0700390 fn = "build/%s.dmg" % title
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700391 d = DiskImage(fn, title)
392 d.symlink('/Applications', '/Applications')
Alexander Afanasyevba87ea32013-07-14 12:27:03 -0700393 d.copy('build/%s/ChronoChat.app' % BINARY_POSTFIX, '/ChronoChat.app')
Zhenkai Zhu9eec5822012-10-02 11:48:12 -0700394 d.create()
395