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