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 if newPath == '/':
48 continue
49 try:
50 os.mkdir(newPath)
51 except OSError as e:
52 if e.errno != errno.EEXIST:
53 raise
54
55
56def parseOtoolLine(line, execPath, root):
57 if not line.startswith('\t'):
58 return None, None, None, None
59 line = line[1:]
60 match = re.match(r'(\S.*) \(compatibility version.*\)', line)
61 path = match.group(1)
62 split = splitPath(path)
63 newExecPath = ['@executable_path', '..', 'Frameworks']
64 newPath = execPath[:-1]
65 newPath.append('Frameworks')
66 if split[:3] == ['/', 'usr', 'lib'] or split[:2] == ['/', 'System']:
67 return None, None, None, None
68 if split[0] == '@executable_path':
69 split[:1] = execPath
70 if split[0] == '/' and not os.access(joinPath(split), os.F_OK):
71 split[:1] = root
72 oldPath = os.path.realpath(joinPath(split))
73 split = splitPath(oldPath)
74 isFramework = False
75 if not split[-1].endswith('.dylib'):
76 isFramework = True
77 split, framework = findFramework(split)
78 newPath.append(split[-1])
79 newExecPath.append(split[-1])
80 if isFramework:
81 newPath.extend(framework)
82 newExecPath.extend(framework)
83 split.extend(framework)
84 newPath = joinPath(newPath)
85 newExecPath = joinPath(newExecPath)
86 return joinPath(split), newPath, path, newExecPath
87
88def updateMachO(bin, execPath, root):
89 global qtPath
90 otoolOutput = subprocess.check_output([otool, '-L', bin])
91 toUpdate = []
92 for line in otoolOutput.split('\n'):
93 oldPath, newPath, oldExecPath, newExecPath = parseOtoolLine(line, execPath, root)
94 if not newPath:
95 continue
96 if os.access(newPath, os.F_OK):
97 if verbose:
98 print('Skipping copying {}, already done.'.format(oldPath))
99 newPath = None
100 elif os.path.abspath(oldPath) != os.path.abspath(newPath):
101 if verbose:
102 print('Copying {} to {}...'.format(oldPath, newPath))
103 parent, child = os.path.split(newPath)
104 makedirs(parent)
105 shutil.copy2(oldPath, newPath)
106 os.chmod(newPath, 0o644)
107 toUpdate.append((newPath, oldExecPath, newExecPath))
108 if not qtPath and 'Qt' in oldPath:
109 qtPath = findQtPath(oldPath)
110 if verbose:
111 print('Found Qt path at {}.'.format(qtPath))
112 args = [installNameTool]
113 for path, oldExecPath, newExecPath in toUpdate:
114 if path != bin:
115 if path:
116 updateMachO(path, execPath, root)
117 if verbose:
118 print('Updating Mach-O load from {} to {}...'.format(oldExecPath, newExecPath))
119 args.extend(['-change', oldExecPath, newExecPath])
120 else:
121 if verbose:
122 print('Updating Mach-O id from {} to {}...'.format(oldExecPath, newExecPath))
123 args.extend(['-id', newExecPath])
124 args.append(bin)
125 subprocess.check_call(args)
126
127if __name__ == '__main__':
128 parser = argparse.ArgumentParser()
129 parser.add_argument('-R', '--root', metavar='ROOT', default='/', help='root directory to search')
130 parser.add_argument('-I', '--install-name-tool', metavar='INSTALL_NAME_TOOL', default='install_name_tool', help='path to install_name_tool')
131 parser.add_argument('-O', '--otool', metavar='OTOOL', default='otool', help='path to otool')
132 parser.add_argument('-p', '--qt-plugins', metavar='PLUGINS', default='', help='Qt plugins to include (comma-separated)')
133 parser.add_argument('-v', '--verbose', action='store_true', default=False, help='output more information')
134 parser.add_argument('bundle', help='application bundle to deploy')
135 args = parser.parse_args()
136
137 otool = args.otool
138 installNameTool = args.install_name_tool
139 verbose = args.verbose
140
141 try:
142 shutil.rmtree(os.path.join(args.bundle, 'Contents/Frameworks/'))
143 except OSError as e:
144 if e.errno != errno.ENOENT:
145 raise
146
147 for executable in os.listdir(os.path.join(args.bundle, 'Contents/MacOS')):
148 if executable.endswith('.dSYM'):
149 continue
150 fullPath = os.path.join(args.bundle, 'Contents/MacOS/', executable)
151 updateMachO(fullPath, splitPath(os.path.join(args.bundle, 'Contents/MacOS')), splitPath(args.root))
152 if args.qt_plugins:
153 try:
154 shutil.rmtree(os.path.join(args.bundle, 'Contents/PlugIns/'))
155 except OSError as e:
156 if e.errno != errno.ENOENT:
157 raise
158 makedirs(os.path.join(args.bundle, 'Contents/PlugIns'))
159 makedirs(os.path.join(args.bundle, 'Contents/Resources'))
160 with open(os.path.join(args.bundle, 'Contents/Resources/qt.conf'), 'w') as conf:
161 conf.write('[Paths]\nPlugins = PlugIns\n')
162 plugins = args.qt_plugins.split(',')
163 for plugin in plugins:
164 plugin = plugin.strip()
165 kind, plug = os.path.split(plugin)
166 newDir = os.path.join(args.bundle, 'Contents/PlugIns/', kind)
167 makedirs(newDir)
168 newPath = os.path.join(newDir, plug)
169 shutil.copy2(os.path.join(qtPath, 'plugins', plugin), newPath)
170 updateMachO(newPath, splitPath(os.path.join(args.bundle, 'Contents/MacOS')), splitPath(args.root))