blob: 536d8417cf2cd13b2c76d709571946f8795bfff3 [file] [log] [blame]
Alexander Afanasyevcf18c802016-03-20 22:48:15 -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
13import platform
14
15if platform.system () != 'Darwin':
16 print "This script is indended to be run only on OSX platform"
17 exit (1)
18
19MIN_SUPPORTED_VERSION="10.10"
20
21current_version = tuple(int(i) for i in platform.mac_ver()[0].split('.')[0:2])
22min_supported_version = tuple(int(i) for i in MIN_SUPPORTED_VERSION.split('.')[0:2])
23
24if current_version < min_supported_version:
25 print "This script is indended to be run only on OSX >= %s platform" % MIN_SUPPORTED_VERSION
26 exit (1)
27
28options = None
29
30def gitrev():
31 return os.popen('git describe').read()[:-1]
32
33def codesign(path):
34 '''Call the codesign executable.'''
35
36 if hasattr(path, 'isalpha'):
37 path = (path,)
38
39 for p in path:
40 p = Popen(('codesign', '-vvvv', '--deep', '--force', '--sign', options.codesign, p))
41 retval = p.wait()
42 if retval != 0:
43 return retval
44 return 0
45
46class AppBundle(object):
47
48 def __init__(self, bundle, version, binary):
49 shutil.copytree (src = binary, dst = bundle, symlinks = True)
50
51 self.framework_path = ''
52 self.handled_libs = {}
53 self.bundle = bundle
54 self.version = version
55 self.infopath = os.path.join(os.path.abspath(bundle), 'Contents', 'Info.plist')
56 self.infoplist = plistlib.readPlist(self.infopath)
57 self.binary = os.path.join(os.path.abspath(bundle), 'Contents', 'MacOS', self.infoplist['CFBundleExecutable'])
58 print ' * Preparing AppBundle'
59
60 def is_system_lib(self, lib):
61 '''
62 Is the library a system library, meaning that we should not include it in our bundle?
63 '''
64 if lib.startswith('/System/Library/'):
65 return True
66 if lib.startswith('/usr/lib/'):
67 return True
68
69 return False
70
71 def is_dylib(self, lib):
72 '''
73 Is the library a dylib?
74 '''
75 return lib.endswith('.dylib')
76
77 def get_framework_base(self, fw):
78 '''
79 Extracts the base .framework bundle path from a library in an abitrary place in a framework.
80 '''
81 paths = fw.split('/')
82 for i, str in enumerate(paths):
83 if str.endswith('.framework'):
84 return '/'.join(paths[:i+1])
85 return None
86
87 def is_framework(self, lib):
88 '''
89 Is the library a framework?
90 '''
91 return bool(self.get_framework_base(lib))
92
93 def get_binary_libs(self, path):
94 '''
95 Get a list of libraries that we depend on.
96 '''
97 m = re.compile('^\t(.*)\ \(.*$')
98 libs = Popen(['otool', '-L', path], stdout=PIPE).communicate()[0]
99 libs = string.split(libs, '\n')
100 ret = []
101 bn = os.path.basename(path)
102 for line in libs:
103 g = m.match(line)
104 if g is not None:
105 lib = g.groups()[0]
106 if lib != bn:
107 ret.append(lib)
108 return ret
109
110 def handle_libs(self):
111 '''
112 Copy non-system libraries that we depend on into our bundle, and fix linker
113 paths so they are relative to our bundle.
114 '''
115 print ' * Taking care of libraries'
116
117 # Does our fwpath exist?
118 fwpath = os.path.join(os.path.abspath(self.bundle), 'Contents', 'Frameworks')
119 if not os.path.exists(fwpath):
120 os.mkdir(fwpath)
121
122 self.handle_binary_libs()
123
124 def handle_binary_libs(self, macho=None, loader_path=None):
125 '''
126 Fix up dylib depends for a specific binary.
127 '''
128 # Does our fwpath exist already? If not, create it.
129 if not self.framework_path:
130 self.framework_path = self.bundle + '/Contents/Frameworks'
131 if not os.path.exists(self.framework_path):
132 os.mkdir(self.framework_path)
133 else:
134 shutil.rmtree(self.framework_path)
135 os.mkdir(self.framework_path)
136
137 # If we weren't explicitly told which binary to operate on, pick the
138 # bundle's default executable from its property list.
139 if macho is None:
140 macho = os.path.abspath(self.binary)
141 else:
142 macho = os.path.abspath(macho)
143
144 print "Processing [%s]" % 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 print "COPY ", fw_path, dst
166 shutil.copytree(fw_path, dst, symlinks=True)
167 if name.startswith('Qt'):
168 os.remove(dst + '/' + name + '.prl')
169 os.remove(dst + '/Headers')
170 shutil.rmtree(dst + '/Versions/Current/Headers')
171
172 os.chmod(abs, 0755)
173 os.system('install_name_tool -id "@executable_path/../Frameworks/%s" "%s"' % (rel, abs))
174 self.handled_libs[basename] = True
175 self.handle_binary_libs(abs)
176
177 os.chmod(macho, 0755)
Alexander Afanasyev2fda1262016-03-20 23:26:23 -0700178 # print 'install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho)
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700179 os.system('install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho))
180
181 # Regular dylibs
182 else:
183 basename = os.path.basename(lib)
184 rel = basename
185
186 if not basename in self.handled_libs:
187 if lib.startswith('@loader_path'):
188 copypath = lib.replace('@loader_path', loader_path)
189 else:
190 copypath = lib
191
192 print "COPY ", copypath
193 shutil.copy(copypath, self.framework_path + '/' + basename)
194
195 abs = self.framework_path + '/' + rel
196 os.chmod(abs, 0755)
197 os.system('install_name_tool -id "@executable_path/../Frameworks/%s" "%s"' % (rel, abs))
198 self.handled_libs[basename] = True
199 self.handle_binary_libs(abs, loader_path=os.path.dirname(lib) if loader_path is None else loader_path)
200
Alexander Afanasyev2fda1262016-03-20 23:26:23 -0700201 # print 'install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho)
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700202 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
260 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
272class 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):
Alexander Afanasyev2fda1262016-03-20 23:26:23 -0700332 os.remove(self.filename)
333 shutil.rmtree(self.filename, ignore_errors=True)
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700334 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('-r', '--release', dest='release', help='Build a release. This determines the version number of the release.')
349 parser.add_option('-s', '--snapshot', dest='snapshot', help='Build a snapshot release. This determines the \'snapshot version\'.')
350 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)
351 parser.add_option('--codesign', dest='codesign', help='Identity to use for code signing. (If not set, no code signing will occur)')
352
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()
364 else:
365 print 'ERROR: Neither snapshot or release selected. Bailing.'
366 parser.print_help ()
367 sys.exit(1)
368
369 # Do the finishing touches to our Application bundle before release
370 shutil.rmtree('build/%s/NDN.app' % (MIN_SUPPORTED_VERSION), ignore_errors=True)
371 a = AppBundle('build/%s/NDN.app' % (MIN_SUPPORTED_VERSION), ver, 'build/NFD Control Center.app')
372 a.copy_qt_plugins()
373 a.handle_libs()
374 a.copy_resources(['qt.conf'])
375 a.set_min_macosx_version('%s.0' % MIN_SUPPORTED_VERSION)
376 a.done()
377
378 # Sign our binaries, etc.
379 if options.codesign:
380 print ' * Signing binaries with identity `%s\'' % options.codesign
381 binaries = (
382 'build/%s/ChronoChat.app' % (MIN_SUPPORTED_VERSION),
383 )
384
385 codesign(binaries)
386 print ''
387
388 # Create diskimage
389 title = "NDN-%s-%s" % (ver, MIN_SUPPORTED_VERSION)
390 fn = "build/%s.dmg" % title
391 d = DiskImage(fn, title)
392 d.symlink('/Applications', '/Applications')
393 d.copy('build/%s/NDN.app' % MIN_SUPPORTED_VERSION, '/NDN.app')
394 d.create()