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