tools/deploy-mac.py (view raw)
1#!/usr/bin/env python
2from __future__ import print_function
3import argparse
4import errno
5import os
6import re
7import shutil
8import subprocess
9
10qtPath = None
11verbose = False
12
13def splitPath(path):
14 folders = []
15 while True:
16 path, folder = os.path.split(path)
17 if folder != '':
18 folders.append(folder)
19 else:
20 if path != '':
21 folders.append(path)
22 break
23 folders.reverse()
24 return folders
25
26def joinPath(path):
27 return reduce(os.path.join, path, '')
28
29def findFramework(path):
30 child = []
31 while path and not path[-1].endswith('.framework'):
32 child.append(path.pop())
33 child.reverse()
34 return path, child
35
36def findQtPath(path):
37 parent, child = findFramework(splitPath(path))
38 return joinPath(parent[:-2])
39
40def makedirs(path):
41 split = splitPath(path)
42 accum = []
43 split.reverse()
44 while split:
45 accum.append(split.pop())
46 newPath = joinPath(accum)
47 try:
48 os.mkdir(newPath)
49 except OSError as e:
50 if e.errno != errno.EEXIST:
51 raise
52
53
54def parseOtoolLine(line, execPath, root):
55 if not line.startswith('\t'):
56 return None, None, None, None
57 line = line[1:]
58 match = re.match('([@/].*) \(compatibility version.*\)', line)
59 path = match.group(1)
60 split = splitPath(path)
61 newExecPath = ['@executable_path', '..', 'Frameworks']
62 newPath = execPath[:-1]
63 newPath.append('Frameworks')
64 if split[:3] == ['/', 'usr', 'lib'] or split[:2] == ['/', 'System']:
65 return None, None, None, None
66 if split[0] == '@executable_path':
67 split[:1] = execPath
68 if split[0] == '/' and not os.access(joinPath(split), os.F_OK):
69 split[:1] = root
70 isFramework = False
71 if not split[-1].endswith('.dylib'):
72 isFramework = True
73 split, framework = findFramework(split)
74 newPath.append(split[-1])
75 newExecPath.append(split[-1])
76 if isFramework:
77 newPath.extend(framework)
78 newExecPath.extend(framework)
79 split.extend(framework)
80 newPath = joinPath(newPath)
81 newExecPath = joinPath(newExecPath)
82 return joinPath(split), newPath, path, newExecPath
83
84def updateMachO(bin, execPath, root):
85 global qtPath
86 otoolOutput = subprocess.check_output([otool, '-L', bin])
87 toUpdate = []
88 for line in otoolOutput.split('\n'):
89 oldPath, newPath, oldExecPath, newExecPath = parseOtoolLine(line, execPath, root)
90 if not newPath:
91 continue
92 if os.access(newPath, os.F_OK):
93 if verbose:
94 print('Skipping copying {}, already done.'.format(oldPath))
95 elif os.path.abspath(oldPath) != os.path.abspath(newPath):
96 if verbose:
97 print('Copying {} to {}...'.format(oldPath, newPath))
98 parent, child = os.path.split(newPath)
99 makedirs(parent)
100 shutil.copy2(oldPath, newPath)
101 os.chmod(newPath, 0o644)
102 toUpdate.append((newPath, oldExecPath, newExecPath))
103 if not qtPath and 'Qt' in oldPath:
104 qtPath = findQtPath(oldPath)
105 if verbose:
106 print('Found Qt path at {}.'.format(qtPath))
107 for path, oldExecPath, newExecPath in toUpdate:
108 if path != bin:
109 updateMachO(path, execPath, root)
110 if verbose:
111 print('Updating Mach-O load from {} to {}...'.format(oldExecPath, newExecPath))
112 subprocess.check_call([installNameTool, '-change', oldExecPath, newExecPath, bin])
113 else:
114 if verbose:
115 print('Updating Mach-O id from {} to {}...'.format(oldExecPath, newExecPath))
116 subprocess.check_call([installNameTool, '-id', newExecPath, bin])
117
118if __name__ == '__main__':
119 parser = argparse.ArgumentParser()
120 parser.add_argument('-R', '--root', metavar='ROOT', default='/', help='root directory to search')
121 parser.add_argument('-I', '--install-name-tool', metavar='INSTALL_NAME_TOOL', default='install_name_tool', help='path to install_name_tool')
122 parser.add_argument('-O', '--otool', metavar='OTOOL', default='otool', help='path to otool')
123 parser.add_argument('-p', '--qt-plugins', metavar='PLUGINS', default='', help='Qt plugins to include (comma-separated)')
124 parser.add_argument('-v', '--verbose', action='store_true', default=False, help='output more information')
125 parser.add_argument('bundle', help='application bundle to deploy')
126 args = parser.parse_args()
127
128 otool = args.otool
129 installNameTool = args.install_name_tool
130 verbose = args.verbose
131
132 try:
133 shutil.rmtree(os.path.join(args.bundle, 'Contents/Frameworks/'))
134 except OSError as e:
135 if e.errno != errno.ENOENT:
136 raise
137
138 for executable in os.listdir(os.path.join(args.bundle, 'Contents/MacOS')):
139 if executable.endswith('.dSYM'):
140 continue
141 fullPath = os.path.join(args.bundle, 'Contents/MacOS/', executable)
142 updateMachO(fullPath, splitPath(os.path.join(args.bundle, 'Contents/MacOS')), splitPath(args.root))
143 if args.qt_plugins:
144 try:
145 shutil.rmtree(os.path.join(args.bundle, 'Contents/PlugIns/'))
146 except OSError as e:
147 if e.errno != errno.ENOENT:
148 raise
149 makedirs(os.path.join(args.bundle, 'Contents/PlugIns'))
150 makedirs(os.path.join(args.bundle, 'Contents/Resources'))
151 with open(os.path.join(args.bundle, 'Contents/Resources/qt.conf'), 'w') as conf:
152 conf.write('[Paths]\nPlugins = PlugIns\n')
153 plugins = args.qt_plugins.split(',')
154 for plugin in plugins:
155 plugin = plugin.strip()
156 kind, plug = os.path.split(plugin)
157 newDir = os.path.join(args.bundle, 'Contents/PlugIns/', kind)
158 makedirs(newDir)
159 newPath = os.path.join(newDir, plug)
160 shutil.copy2(os.path.join(qtPath, 'plugins', plugin), newPath)
161 updateMachO(newPath, splitPath(os.path.join(args.bundle, 'Contents/MacOS')), splitPath(args.root))