blob: fe4e64a191a125ab9dcb68971d9140139bc6dd2f [file] [log] [blame]
Yukai Tuc1a93332017-03-17 23:33:19 -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
13os.environ['PATH'] += ":/usr/local/opt/qt5/bin:/opt/qt5/5.8/clang_64/bin"
14
15import platform
16
17if platform.system () != 'Darwin':
18 print "This script is indended to be run only on OSX platform"
19 exit (1)
20
21MIN_SUPPORTED_VERSION="10.12"
22
23current_version = tuple(int(i) for i in platform.mac_ver()[0].split('.')[0:2])
24min_supported_version = tuple(int(i) for i in MIN_SUPPORTED_VERSION.split('.')[0:2])
25
26if current_version < min_supported_version:
27 print "This script is indended to be run only on OSX >= %s platform" % MIN_SUPPORTED_VERSION
28 exit (1)
29
30options = None
31
32def gitrev():
33 return os.popen('git describe').read()[:-1]
34
35def codesign(path):
36 '''Call the codesign executable.'''
37
38 if hasattr(path, 'isalpha'):
39 path = (path,)
40
41 for p in path:
42 p = Popen(('codesign', '-vvvv', '--deep', '--force', '--sign', options.codesign, p))
43 retval = p.wait()
44 if retval != 0:
45 return retval
46 return 0
47
48class AppBundle(object):
49
50 def __init__(self, bundle, version, binary):
51 shutil.copytree (src = binary, dst = bundle, symlinks = True)
52
53 self.framework_path = ''
54 self.handled_libs = {}
55 self.bundle = bundle
56 self.version = version
57 self.infopath = os.path.join(os.path.abspath(bundle), 'Contents', 'Info.plist')
58 self.infoplist = plistlib.readPlist(self.infopath)
59 self.binary = os.path.join(os.path.abspath(bundle), 'Contents', 'MacOS', self.infoplist['CFBundleExecutable'])
60 print ' * Preparing AppBundle'
61
62 def is_system_lib(self, lib):
63 '''
64 Is the library a system library, meaning that we should not include it in our bundle?
65 '''
66 if lib.startswith('/System/Library/'):
67 return True
68 if lib.startswith('/usr/lib/'):
69 return True
70
71 return False
72
73 def is_dylib(self, lib):
74 '''
75 Is the library a dylib?
76 '''
77 return lib.endswith('.dylib')
78
79 def get_framework_base(self, fw):
80 '''
81 Extracts the base .framework bundle path from a library in an abitrary place in a framework.
82 '''
83 paths = fw.split('/')
84 for i, str in enumerate(paths):
85 if str.endswith('.framework'):
86 return '/'.join(paths[:i+1])
87 return None
88
89 def is_framework(self, lib):
90 '''
91 Is the library a framework?
92 '''
93 return bool(self.get_framework_base(lib))
94
95 def get_binary_libs(self, path):
96 '''
97 Get a list of libraries that we depend on.
98 '''
99 m = re.compile('^\t(.*)\ \(.*$')
100 libs = Popen(['otool', '-L', path], stdout=PIPE).communicate()[0]
101 libs = string.split(libs, '\n')
102 ret = []
103 bn = os.path.basename(path)
104 for line in libs:
105 g = m.match(line)
106 if g is not None:
107 lib = g.groups()[0]
108 if lib != bn:
109 ret.append(lib)
110 return ret
111
112 def handle_libs(self):
113 '''
114 Copy non-system libraries that we depend on into our bundle, and fix linker
115 paths so they are relative to our bundle.
116 '''
117 print ' * Taking care of libraries'
118
119 # Does our fwpath exist?
120 fwpath = os.path.join(os.path.abspath(self.bundle), 'Contents', 'Frameworks')
121 if not os.path.exists(fwpath):
122 os.mkdir(fwpath)
123
124 self.handle_binary_libs()
125
126 def handle_binary_libs(self, macho=None, loader_path=None):
127 '''
128 Fix up dylib depends for a specific binary.
129 '''
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 print "Processing [%s]" % macho
147
148 libs = self.get_binary_libs(macho)
149
150 for lib in libs:
151
152 # Skip system libraries
153 if self.is_system_lib(lib):
154 continue
155
156 if 'Qt' in lib:
157 continue
158
159 # Frameworks are 'special'.
160 if self.is_framework(lib):
161 fw_path = self.get_framework_base(lib)
162 basename = os.path.basename(fw_path)
163 name = basename.split('.framework')[0]
164 rel = basename + '/' + name
165
166 abs = self.framework_path + '/' + rel
167
168 if not basename in self.handled_libs:
169 dst = self.framework_path + '/' + basename
170 print "COPY ", fw_path, dst
171 shutil.copytree(fw_path, dst, symlinks=True)
172 if name.startswith('Qt'):
173 os.remove(dst + '/' + name + '.prl')
174 os.remove(dst + '/Headers')
175 shutil.rmtree(dst + '/Versions/Current/Headers')
176
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
182 os.chmod(macho, 0755)
183 # print 'install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho)
184 os.system('install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho))
185
186 # Regular dylibs
187 else:
188 basename = os.path.basename(lib)
189 rel = basename
190
191 if not basename in self.handled_libs:
192 if lib.startswith('@loader_path'):
193 copypath = lib.replace('@loader_path', loader_path)
194 else:
195 copypath = lib
196
197 print "COPY ", copypath
198 shutil.copy(copypath, self.framework_path + '/' + basename)
199
200 abs = self.framework_path + '/' + rel
201 os.chmod(abs, 0755)
202 os.system('install_name_tool -id "@executable_path/../Frameworks/%s" "%s"' % (rel, abs))
203 self.handled_libs[basename] = True
204 self.handle_binary_libs(abs, loader_path=os.path.dirname(lib))
205
206 # print 'install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho)
207 os.chmod(macho, 0755)
208 os.system('install_name_tool -change "%s" "@executable_path/../Frameworks/%s" "%s"' % (lib, rel, macho))
209
210 def copy_resources(self, rsrcs):
211 '''
212 Copy needed resources into our bundle.
213 '''
214 print ' * Copying needed resources'
215 rsrcpath = os.path.join(self.bundle, 'Contents', 'Resources')
216 if not os.path.exists(rsrcpath):
217 os.mkdir(rsrcpath)
218
219 # Copy resources already in the bundle
220 for rsrc in rsrcs:
221 b = os.path.basename(rsrc)
222 if os.path.isdir(rsrc):
223 shutil.copytree(rsrc, os.path.join(rsrcpath, b), symlinks=True)
224 elif os.path.isfile(rsrc):
225 shutil.copy(rsrc, os.path.join(rsrcpath, b))
226
227 return
228
229 def copy_etc(self, rsrcs):
230 '''
231 Copy needed config files into our bundle.
232 '''
233 print ' * Copying needed config files'
234 rsrcpath = os.path.join(self.bundle, 'Contents', 'etc', 'ndn')
235 if not os.path.exists(rsrcpath):
236 os.makedirs(rsrcpath)
237
238 # Copy resources already in the bundle
239 for rsrc in rsrcs:
240 b = os.path.basename(rsrc)
241 if os.path.isdir(rsrc):
242 shutil.copytree(rsrc, os.path.join(rsrcpath, b), symlinks=True)
243 elif os.path.isfile(rsrc):
244 shutil.copy(rsrc, os.path.join(rsrcpath, b))
245
246 return
247
248 def copy_framework(self, framework):
249 '''
250 Copy frameworks
251 '''
252 print ' * Copying framework'
253 rsrcpath = os.path.join(self.bundle, 'Contents', 'Frameworks', os.path.basename(framework))
254
255 shutil.copytree(framework, rsrcpath, symlinks = True)
256
257 def macdeployqt(self):
258 Popen(['macdeployqt', self.bundle, '-qmldir=src', '-executable=%s' % self.binary]).communicate()
259
260 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 = os.path.join(path, 'bin')
267 dst = os.path.join(self.bundle, 'Contents', 'Platform')
268 shutil.copytree(src, dst, symlinks=False)
269
270 for subdir, dirs, files in os.walk(dst):
271 for file in files:
272 abs = subdir + "/" + file
273 self.handle_binary_libs(abs)
274
275 def set_min_macosx_version(self, version):
276 '''
277 Set the minimum version of Mac OS X version that this App will run on.
278 '''
279 print ' * Setting minimum Mac OS X version to: %s' % (version)
280 self.infoplist['LSMinimumSystemVersion'] = version
281
282 def done(self):
283 plistlib.writePlist(self.infoplist, self.infopath)
284 print ' * Done!'
285 print ''
286
287class FolderObject(object):
288 class Exception(exceptions.Exception):
289 pass
290
291 def __init__(self):
292 self.tmp = tempfile.mkdtemp()
293
294 def copy(self, src, dst='/'):
295 '''
296 Copy a file or directory into foler
297 '''
298 asrc = os.path.abspath(src)
299
300 if dst[0] != '/':
301 raise self.Exception
302
303 # Determine destination
304 if dst[-1] == '/':
305 adst = os.path.abspath(self.tmp + '/' + dst + os.path.basename(src))
306 else:
307 adst = os.path.abspath(self.tmp + '/' + dst)
308
309 if os.path.isdir(asrc):
310 print ' * Copying directory: %s' % os.path.basename(asrc)
311 shutil.copytree(asrc, adst, symlinks=True)
312 elif os.path.isfile(asrc):
313 print ' * Copying file: %s' % os.path.basename(asrc)
314 shutil.copy(asrc, adst)
315
316 def symlink(self, src, dst):
317 '''
318 Create a symlink inside the folder
319 '''
320 asrc = os.path.abspath(src)
321 adst = self.tmp + '/' + dst
322 print " * Creating symlink %s" % os.path.basename(asrc)
323 os.symlink(asrc, adst)
324
325 def mkdir(self, name):
326 '''
327 Create a directory inside the folder.
328 '''
329 print ' * Creating directory %s' % os.path.basename(name)
330 adst = self.tmp + '/' + name
331 os.makedirs(adst)
332
333class DiskImage(FolderObject):
334
335 def __init__(self, filename, volname):
336 FolderObject.__init__(self)
337 print ' * Preparing to create diskimage'
338 self.filename = filename
339 self.volname = volname
340
341 def create(self):
342 '''
343 Create the disk image
344 '''
345 print ' * Creating disk image. Please wait...'
346 if os.path.exists(self.filename):
347 os.remove(self.filename)
348 shutil.rmtree(self.filename, ignore_errors=True)
349 p = Popen(['hdiutil', 'create',
350 '-srcfolder', self.tmp,
351 '-format', 'UDBZ',
352 '-volname', self.volname,
353 self.filename])
354
355 retval = p.wait()
356 print ' * Removing temporary directory.'
357 shutil.rmtree(self.tmp)
358 print ' * Done!'
359
360
361if __name__ == '__main__':
362 parser = OptionParser()
363 parser.add_option('-r', '--release', dest='release', help='Build a release. This determines the version number of the release.')
364 parser.add_option('-s', '--snapshot', dest='snapshot', help='Build a snapshot release. This determines the \'snapshot version\'.')
365 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)
366 parser.add_option('--no-dmg', dest='no_dmg', action='store_true', default=False, help='''Disable creation of DMG''')
367 parser.add_option('--codesign', dest='codesign', help='Identity to use for code signing. (If not set, no code signing will occur)')
368
369 options, args = parser.parse_args()
370
371 # Release
372 if options.release:
373 ver = options.release
374 # Snapshot
375 elif options.snapshot or options.git:
376 if not options.git:
377 ver = options.snapshot
378 else:
379 ver = gitrev()
380 else:
381 print 'ERROR: Neither snapshot or release selected. Bailing.'
382 parser.print_help ()
383 sys.exit(1)
384
385 # Do the finishing touches to our Application bundle before release
386 shutil.rmtree('build/dist/ChronoShare.app', ignore_errors=True)
387 a = AppBundle('build/dist/ChronoShare.app', ver, 'build/ChronoShare.app')
388 # a.copy_resources(['qt.conf'])
389 a.set_min_macosx_version('%s.0' % MIN_SUPPORTED_VERSION)
390 a.handle_binary_libs()
391 a.macdeployqt()
392 a.copy_framework("osx/Frameworks/Sparkle.framework")
393 a.done()
394
395 # Sign our binaries, etc.
396 if options.codesign:
397 print ' * Signing binaries with identity `%s\'' % options.codesign
398 codesign(a.bundle)
399 print ''
400
401 if not options.no_dmg:
402 # Create diskimage
403 title = "ChronoShare-%s" % ver
404 fn = "build/%s.dmg" % title
405 d = DiskImage(fn, title)
406 d.symlink('/Applications', '/Applications')
407 d.copy('build/dist/ChronoShare.app', '/ChronoShare.app')
408 d.create()
409
410 if options.codesign:
411 print ' * Signing .dmg with identity `%s\'' % options.codesign
412 codesign(fn)
413 print ''
414
415Popen('tail -n +3 RELEASE_NOTES.md | pandoc -f markdown -t html > build/release-notes-%s.html' % ver, shell=True).wait()