blob: 8df5b41e3d4dda948c7935776d2e24f4ab3312b6 [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
Alexander Afanasyevb2cf5c02016-03-21 11:04:28 -0700260 def copy_ndn_deps(self, path):
261 '''
262 Copy over NDN dependencies (NFD and related apps)
263 '''
264 print ' * Copying NDN dependencies'
265
266 src = path
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700267 dst = os.path.join(self.bundle, 'Contents', 'Resources', 'platform')
Alexander Afanasyevb2cf5c02016-03-21 11:04:28 -0700268 shutil.copytree(src, dst, symlinks=False)
269
270 top = dst
271 files = {}
272
273 def cb(arg, dirname, fnames):
274 if dirname == top:
275 return
276 files[dirname] = fnames
277
278 os.path.walk(top, cb, None)
279
280 # Cleanup debug folders stuff
281 excludeDirs = ['include', 'pkgconfig']
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700282 excludeFiles = ['libndn-cxx.dylib', 'nfd-start', 'nfd-stop']
Alexander Afanasyevb2cf5c02016-03-21 11:04:28 -0700283
284 for dir, files in files.items():
285 basename = os.path.basename(dir)
286 if basename in excludeDirs:
287 shutil.rmtree(dir)
288 continue
289 for file in files:
290 if file in excludeFiles:
291 abs = dir + '/' + file
292 os.remove(abs)
293
294 top = dst
295 files = {}
296
297 os.path.walk(top, cb, None)
298
299 for dir, files in files.items():
300 for file in files:
301 abs = dir + '/' + file
302 type = Popen(['file', '-b', abs], stdout=PIPE).communicate()[0].strip()
303 if type.startswith('Mach-O'):
304 self.handle_binary_libs(abs)
305
306
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700307 def set_min_macosx_version(self, version):
308 '''
309 Set the minimum version of Mac OS X version that this App will run on.
310 '''
311 print ' * Setting minimum Mac OS X version to: %s' % (version)
312 self.infoplist['LSMinimumSystemVersion'] = version
313
314 def done(self):
315 plistlib.writePlist(self.infoplist, self.infopath)
316 print ' * Done!'
317 print ''
318
319class FolderObject(object):
320 class Exception(exceptions.Exception):
321 pass
322
323 def __init__(self):
324 self.tmp = tempfile.mkdtemp()
325
326 def copy(self, src, dst='/'):
327 '''
328 Copy a file or directory into foler
329 '''
330 asrc = os.path.abspath(src)
331
332 if dst[0] != '/':
333 raise self.Exception
334
335 # Determine destination
336 if dst[-1] == '/':
337 adst = os.path.abspath(self.tmp + '/' + dst + os.path.basename(src))
338 else:
339 adst = os.path.abspath(self.tmp + '/' + dst)
340
341 if os.path.isdir(asrc):
342 print ' * Copying directory: %s' % os.path.basename(asrc)
343 shutil.copytree(asrc, adst, symlinks=True)
344 elif os.path.isfile(asrc):
345 print ' * Copying file: %s' % os.path.basename(asrc)
346 shutil.copy(asrc, adst)
347
348 def symlink(self, src, dst):
349 '''
350 Create a symlink inside the folder
351 '''
352 asrc = os.path.abspath(src)
353 adst = self.tmp + '/' + dst
354 print " * Creating symlink %s" % os.path.basename(asrc)
355 os.symlink(asrc, adst)
356
357 def mkdir(self, name):
358 '''
359 Create a directory inside the folder.
360 '''
361 print ' * Creating directory %s' % os.path.basename(name)
362 adst = self.tmp + '/' + name
363 os.makedirs(adst)
364
365class DiskImage(FolderObject):
366
367 def __init__(self, filename, volname):
368 FolderObject.__init__(self)
369 print ' * Preparing to create diskimage'
370 self.filename = filename
371 self.volname = volname
372
373 def create(self):
374 '''
375 Create the disk image
376 '''
377 print ' * Creating disk image. Please wait...'
378 if os.path.exists(self.filename):
Alexander Afanasyev2fda1262016-03-20 23:26:23 -0700379 os.remove(self.filename)
380 shutil.rmtree(self.filename, ignore_errors=True)
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700381 p = Popen(['hdiutil', 'create',
382 '-srcfolder', self.tmp,
383 '-format', 'UDBZ',
384 '-volname', self.volname,
385 self.filename])
386
387 retval = p.wait()
388 print ' * Removing temporary directory.'
389 shutil.rmtree(self.tmp)
390 print ' * Done!'
391
392
393if __name__ == '__main__':
394 parser = OptionParser()
395 parser.add_option('-r', '--release', dest='release', help='Build a release. This determines the version number of the release.')
396 parser.add_option('-s', '--snapshot', dest='snapshot', help='Build a snapshot release. This determines the \'snapshot version\'.')
397 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)
398 parser.add_option('--codesign', dest='codesign', help='Identity to use for code signing. (If not set, no code signing will occur)')
399
400 options, args = parser.parse_args()
401
402 # Release
403 if options.release:
404 ver = options.release
405 # Snapshot
406 elif options.snapshot or options.git:
407 if not options.git:
408 ver = options.snapshot
409 else:
410 ver = gitrev()
411 else:
412 print 'ERROR: Neither snapshot or release selected. Bailing.'
413 parser.print_help ()
414 sys.exit(1)
415
416 # Do the finishing touches to our Application bundle before release
417 shutil.rmtree('build/%s/NDN.app' % (MIN_SUPPORTED_VERSION), ignore_errors=True)
418 a = AppBundle('build/%s/NDN.app' % (MIN_SUPPORTED_VERSION), ver, 'build/NFD Control Center.app')
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700419 a.copy_qt_plugins()
420 a.handle_libs()
Alexander Afanasyevb2cf5c02016-03-21 11:04:28 -0700421 a.copy_ndn_deps("build/deps")
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700422 a.copy_resources(['qt.conf'])
423 a.set_min_macosx_version('%s.0' % MIN_SUPPORTED_VERSION)
424 a.done()
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700425
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700426 # Sign our binaries, etc.
427 if options.codesign:
428 print ' * Signing binaries with identity `%s\'' % options.codesign
429 binaries = (
430 'build/%s/ChronoChat.app' % (MIN_SUPPORTED_VERSION),
431 )
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700432
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700433 codesign(binaries)
434 print ''
Alexander Afanasyevcf18c802016-03-20 22:48:15 -0700435
Alexander Afanasyev11ae34d2016-03-21 11:55:16 -0700436 # Create diskimage
437 title = "NDN-%s-%s" % (ver, MIN_SUPPORTED_VERSION)
438 fn = "build/%s.dmg" % title
439 d = DiskImage(fn, title)
440 d.symlink('/Applications', '/Applications')
441 d.copy('build/%s/NDN.app' % MIN_SUPPORTED_VERSION, '/NDN.app')
442 d.create()