1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
|
"""OSConsX.py - scons support for building applications on OS X using SCons.
Functions to build .app bundles and .dmg images, and to use otool(1) to trace out the needed libraries.
usage:
env = Environment(tools = ['OSConsX', toolpath=['path/to/osconsx'])
env.App('
By <nick@kousu.ca> January 16th 2009
License: 2-clause BSD (XXX put a proper notice here)
Please email me with questions/comments/patches!
TODO:
-add a CheckFramework() call that looks for a framework (and maybe adds to CXXFLAGS||CPPATH||LINKFLAGS if found)
"""
import sys, os, shutil, stat
import SCons
from SCons.Builder import Builder
from SCons.Script import *
import otool
#Dev info:
#http://doc.trolltech.com/qq/qq09-mac-deployment.html
#http://www.scons.org/wiki/MacOSX (not very featureful, but the tip about resource forks might be important (wait did I say important? I meant out of date. see CpMac(1))
#oooh, you can use warnings! just call "warn()"
def system(s):
"wrap system() to give us feedback on what it's doing"
"anything using this call should be fixed to use SCons's declarative style (once you figure that out, right nick?)"
print(s),
sys.stdout.flush() #ignore line buffering..
result = os.system(s)
print
return result
def no_sources(target, source, env):
"an emitter that forces null sources, so that we don't need to have the user explicitly say there are no dependencies (SCons assumes that if you are building 'X.out' then you need 'X.in')"
return target, []
def InstallDir(target, source, env): #XXX this belongs not in this module
"copies the given source dir inside of the given target dir"
#XXX could be rewritten better with schemey-recursion as "if source is File: env.Install(), elif source is Dir, scan the dir and recurse"
#SCons doesn't really like using directories as targets. Like, at all.
#Mkdir(os.path.join(str(target), str(source)))
#translate install(a/, b/) to install(a/b/, [files in b])
contents = Glob(os.path.join(str(source), "*")) #XXX there's probably a cleaner way that SCons has to do this
#print("contents:", contents)
files = filter(lambda f: isinstance(f, SCons.Node.FS.File), contents)
folders = filter(lambda f: isinstance(f, SCons.Node.FS.Dir), contents)
#print(map(str, folders))
name = os.path.basename(str(source))
#install the files local to this
nodes = env.Install(Dir(os.path.join(str(target), name)), files)
#now recursively install the subfolders
for f in folders:
nodes+=InstallDir(Dir(os.path.join(str(target), name)), f, env)
return nodes
#okay, this works. It could be done better (make better use of SCons's declarativity, look at http://frungy.org/~tpot/weblog/2008/05/02#scons-rpm2 for ideas)
#Specifically, this does file copying by itself, instead of telling SCons about it.
#On the other hand, the files it is copying are not really part of the build process, they are tmp files, so maybe it works....
#BUG: scons doesn't track that it's built the .dmg. It decides it needs to build it every time "because it doesn't exist". Perhaps has to do with the lack s
def build_dmg(target, source, env):
"takes the given source files, makes a temporary directory, copies them all there, and then packages that directory into a .dmg"
#TODO: make emit_dmg emit that we are making the Dmg that we are making
#since we are building into a single .dmg, coerce target to point at the actual name
assert len(target) == 1
target = target[0]
# I'm going to let us overwrite the .dmg for now - Albert
#if os.path.exists(str(target)+".dmg"): #huhh? why do I have to say +.dmg here? I thought scons was supposed to handle that
# raise Exception(".dmg target already exists.")
#if 'DMG_DIR' in env: .... etc fill me in please
dmg = os.tmpnam()+"-"+env['VOLNAME'].strip()+"-dmg" #create a directory to build the .dmg root from
#is os.system the best thing for this? Can't we declare that these files need to be moved somehow?
#aah there must be a more SCons-ey (i.e. declarative) way to do all this; the trouble with doing
os.mkdir(dmg)
for f in source:
print("Copying", f)
a, b = str(f), os.path.join(dmg, os.path.basename(str(f.path)))
if isinstance(f, SCons.Node.FS.Dir): #XXX there's a lot of cases that could throw this off, particularly if you try to pass in subdirs
copier = shutil.copytree
elif isinstance(f, SCons.Node.FS.File):
copier = shutil.copy
else:
raise Exception("%s is neither Dir nor File node? Bailing out." % f)
try:
copier(a, b)
except Exception as e:
print("ERRRR", e)
raise Exception("Error copying %s: " % (a,), e)
# Symlink Applications to /Applications
os.system('ln -s /Applications %s' % os.path.join(dmg, 'Applications'))
if env['ICON']:
env['ICON'] = File(str(env['ICON'])) #make sure the given file is an icon; scons does this wrapping for us on sources and targets but not on environment vars (obviously, that would be stupid).
#XXX this doesn't seem to work, at least not on MacOS 10.5
#the MacFUSE people have solved it, though, see "._" in http://www.google.com/codesearch/p?hl=en#OXKFx3-7cSY/tags/macfuse-1.0.0/filesystems-objc/FUSEObjC/FUSEFileSystem.m&q=volumeicon
#appearently it requires making a special volume header file named "._$VOLNAME" with a binary blob in it
#But also the Qt4 dmg has a working icon, and it has no ._$VOLNAME file
shutil.copy(str(env['ICON']), os.path.join(dmg, ".VolumeIcon.icns")) #XXX bug: will crash if not given an icon file
system('SetFile -a C "%s"' % dmg) #is there an sconsey way to declare this? Would be nice so that it could write what
# TODO(rryan): hdiutil has a bug where if srcfolder is greater than 100M it
# fails to create a DMG with error -5341. The actual size of the resulting
# DMG is not affected by the -size parameter -- I think it's just the size
# of the "partition" in the DMG. Hard-coding 150M is a band-aid to get the
# build working again while we figure out the right solution.
if system("hdiutil create -size 150M -srcfolder %s -format UDBZ -ov -volname %s %s" % (dmg, env['VOLNAME'], target)):
raise Exception("hdiutil create failed")
shutil.rmtree(dmg)
Dmg = Builder(action = build_dmg, suffix=".dmg")
class Bundle(SCons.Node.Node):
"until SCons gets its shit together and is able to handle having directories as targets, we use this"
def __init__(self, path):
path = str(path) #decast the object from being a File or a Dir
self.path = path
SCons.Node.Node.__init__(self)
self.clear()
assert self.path == path, "Node constructor overwrote .path :("
def __str__(self):
return self.path
def __repr__(self):
return 'Bundle("%s")' % self.path
def write_file(target, source, env):
data = env['DATA']
for t in target:
f = open(str(t), "wb")
f.write(data)
f.close()
#should be in a different module, really
Writer = Builder(action = write_file, emitter = no_sources)
def build_app(target, source, env):
"""
PLUGINS - a list of plugins to install; as a feature/hack/bug (inspired by Qt, but probably needed by other libs) you can pass a tuple where the first is the file/node and the second is the folder under PlugIns/ that you want it installed to
"""
#TODO: make it strip(1) the installed binary (saves about 1Mb)
#EEEP: this code is pretty flakey because I can't figure out how to force; have asked the scons list about it
#This doesn't handle Frameworks correctly, only .dylibs
#useful to know: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkAnatomy.html#//apple_ref/doc/uid/20002253
#^ so you do have to copy in and _entire_ framework to be sure...
#but for some frameworks it's okay to pretend they are regular
bundle = target[0]
binary = source[0]
#this is copied from emit_app, which is unfortunate
contents = Dir(os.path.join(str(bundle), "Contents"))
MacOS = Dir(os.path.join(str(contents), "MacOS/"))
frameworks = Dir(os.path.join(str(contents), "Frameworks")) #we put both frameworks and standard unix sharedlibs in here
plugins = Dir(os.path.join(str(contents), "PlugIns"))
#installed_bin = source[-1] #env['APP_INSTALLED_BIN']
installed_bin = os.path.join(str(MacOS), os.path.basename(str(binary)))
strip = bool(env.get('STRIP',False))
otool_local_paths = env.get('OTOOL_LOCAL_PATHS', [])
otool_system_paths = env.get('OTOOL_SYSTEM_PATHS', [])
"todo: expose the ability to override the list of System dirs"
#ugh, I really don't like this... I wish I could package it up nicer. I could use a Builder but then I would have to pass in to the builder installed_bin which seems backwards since
#could we use patch_lib on the initial binary itself????
def embed_lib(abs):
"get the path to embed library abs in the bundle"
name = os.path.basename(abs)
return os.path.join(str(frameworks), name)
def relative(emb):
"compute the path of the given embedded binary relative to the binary, i.e. @executable_path/../+..."
# assume that we start in X.app/Contents/, since we know necessarily that @executable_path/../ gives us that
# so then we only need
base = os.path.abspath(str(installed_bin))
emb = os.path.abspath(emb) #XXX is abspath really necessary?
down = emb[len(os.path.commonprefix([base, emb])):] #the path from Contents/ down to the file. Since we are taking away the length of the common prefix we are left with only what is unique to the embedded library's path
return os.path.join("@executable_path/../", down)
#todo: precache all this shit, in case we have to change the install names of a lot of libraries
def automagic_references(embedded): #XXX bad name
"modify a binary file to patch up all it's references"
for ref in otool.dependencies(embedded):
if ref in locals:
embd = locals[ref][1] #the path that this reference is getting embedded at
otool.change_ref(str(embedded), ref, relative(embd))
def patch_lib(embedded):
otool.change_id(embedded, relative(embedded)) #change the name the library knows itself as
automagic_references(embedded)
if strip: #XXX stripping seems to only work on libs compiled a certain way, todo: try out ALL the options, see if can adapt it to work on every sort of lib
system("strip -S '%s' 2>/dev/null" % embedded), #(the stripping fails with ""symbols referenced by relocation entries that can't be stripped"" for some obscure Apple-only reason sometimes, related to their hacks to gcc---it depends on how the file was compiled; since we don't /really/ care about this we just let it silently fail)
#Workarounds for a bug/feature in SCons such that it doesn't necessarily run the source builders before the target builders (wtf scons??)
Execute(Mkdir(contents))
Execute(Mkdir(MacOS))
Execute(Mkdir(frameworks))
Execute(Mkdir(plugins))
#XXX locals should be keyed by absolute path to the lib, not by reference; that way it's easy to tell when a lib referenced in two different ways is actually the same
#XXX rename locals => embeds
#precache the list of names of libs we are using so we can figure out if a lib is local or not (and therefore a ref to it needs to be updated) #XXX it seems kind of wrong to only look at the basename (even if, by the nature of libraries, that must be enough) but there is no easy way to compute the abspath
locals = {} # [ref] => (absolute_path, embedded_path) (ref is the original reference from looking at otool -L; we use this to decide if two libs are the same)
#XXX it would be handy if embed_dependencies returned the otool list for each ref it reads..
for ref, path in otool.embed_dependencies(str(binary), LOCAL=otool_local_paths, SYSTEM=otool_system_paths):
locals[ref] = (path, embed_lib(path))
plugins_l = [] #XXX bad name #list of tuples (source, embed) of plugins to stick under the plugins/ dir
for p in env['PLUGINS']: #build any necessary dirs for plugins (siiiigh)
embedded_p = os.path.join(str(plugins), os.path.base
|