-
Notifications
You must be signed in to change notification settings - Fork 35
/
build_app.py
2633 lines (2277 loc) · 94.5 KB
/
build_app.py
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Mac OS X .app build command for distutils
Originally (loosely) based on code from py2exe's build_exe.py by Thomas Heller.
"""
from __future__ import print_function
import collections
import imp
import os
import plistlib
import shlex
import shutil
import sys
import types
import zipfile
from distutils import log
from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from distutils.sysconfig import get_config_h_filename, get_config_var
from distutils.util import convert_path, get_platform
from itertools import chain
import macholib.dyld
import macholib.MachO
import macholib.MachOStandalone
import pkg_resources
from macholib.util import flipwritable
from modulegraph import modulegraph, zipio
from modulegraph.find_modules import find_modules, find_needed_modules, parse_mf_results
from modulegraph.modulegraph import Package, Script, SourceModule
from modulegraph.util import imp_find_module
from setuptools import Command
from py2app import recipes
from py2app._pkg_meta import IGNORED_DISTINFO, scan_for_metadata
from py2app.apptemplate.setup import main as script_executable
from py2app.create_appbundle import create_appbundle
from py2app.create_pluginbundle import create_pluginbundle
from py2app.filters import has_filename_filter, not_stdlib_filter
from py2app.util import (
byte_compile,
codesign_adhoc,
copy_file,
copy_resource,
copy_tree,
fancy_split,
find_version,
fsencoding,
in_system_path,
iter_platform_files,
make_exec,
make_loader,
make_symlink,
makedirs,
mapc,
mergecopy,
momc,
skipscm,
strip_files,
)
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
PYTHONFRAMEWORK = get_config_var("PYTHONFRAMEWORK")
PLUGIN_SUFFIXES = {
".qlgenerator": "QuickLook",
".mdimporter": "Spotlight",
".xpc": "XPCServices",
".service": "Services",
".prefPane": "PreferencePanes",
".iaplugin": "InternetAccounts",
".action": "Automator",
}
try:
basestring
except NameError:
basestring = str
if hasattr(sys, "real_prefix"):
sys_base_prefix = sys.real_prefix
elif hasattr(sys, "base_prefix"):
sys_base_prefix = sys.base_prefix
else:
sys_base_prefix = sys.prefix
def finalize_distribution_options(dist):
"""
setuptools.finalize_distribution_options extension
point for py2app, to deail with autodiscovery in
setuptools 61.
This addin will set the name and py_modules attributes
when a py2app distribution is detected that does not
yet have these attributes.
are not already set
"""
if (getattr(dist, "app", None) is None and
getattr(dist, "plugin", None) is None):
return
if getattr(dist.metadata, "py_modules", None) is None:
dist.py_modules = []
name = getattr(dist.metadata, "name", None)
if name is None or name == "UNKNOWN":
if dist.app:
targets = FixupTargets(dist.app, "script")
else:
targets = FixupTargets(dist.plugin, "script")
base = targets[0].get_dest_base()
name = os.path.basename(base)
dist.metadata.name = name
def loader_paths(sourcefn, destfn):
# Yield (sourcefn, destfn) pairs for all
# '@loader_path' load commands in 'sourcefn'
sourcedir = os.path.dirname(sourcefn)
destdir = os.path.dirname(destfn)
m = macholib.MachO.MachO(sourcefn)
for header in m.headers:
for _idx, _name, other in header.walkRelocatables():
if not other.startswith("@loader_path/"):
continue
relpath = other[13:]
yield os.path.join(sourcedir, relpath), os.path.join(destdir, relpath)
def rewrite_tkinter_load_commands(tkinter_path):
m = macholib.MachO.MachO(tkinter_path)
tcl_path = None
tk_path = None
rewrite_map = {}
for header in m.headers:
for _idx, _name, other in header.walkRelocatables():
if other.endswith("/Tk"):
if tk_path is not None and other != tk_path:
raise DistutilsPlatformError(
"_tkinter is linked to different Tk paths"
)
tk_path = other
elif other.endswith("/Tcl"):
if tcl_path is not None and other != tcl_path:
raise DistutilsPlatformError(
"_tkinter is linked to different Tcl paths"
)
tcl_path = other
if tcl_path is None or "Tcl.framework" not in tcl_path:
raise DistutilsPlatformError("_tkinter is not linked a Tcl.framework")
if tk_path is None or "Tk.framework" not in tk_path:
raise DistutilsPlatformError("_tkinter is not linked a Tk.framework")
system_tcl_versions = [
nm
for nm in os.listdir("/System/Library/Frameworks/Tcl.framework/Versions")
if nm != "Current"
]
system_tk_versions = [
nm
for nm in os.listdir("/System/Library/Frameworks/Tk.framework/Versions")
if nm != "Current"
]
if not tcl_path.startswith("/System/Library/Frameworks"):
# ../Versions/8.5/Tcl
ver = os.path.basename(os.path.dirname(tcl_path))
if ver not in system_tcl_versions:
raise DistutilsPlatformError(
"_tkinter is linked to a version of Tcl not in /System"
)
rewrite_map[
tcl_path
] = "/System/Library/Frameworks/Tcl.framework/Versions/%s/Tcl" % (ver,)
if not tk_path.startswith("/System/Library/Frameworks"):
# ../Versions/8.5/Tk
ver = os.path.basename(os.path.dirname(tk_path))
if ver not in system_tk_versions:
raise DistutilsPlatformError(
"_tkinter is linked to a version of Tk not in /System"
)
rewrite_map[
tk_path
] = "/System/Library/Frameworks/Tk.framework/Versions/%s/Tk" % (ver,)
if rewrite_map:
print("Relinking _tkinter.so to system Tcl/Tk")
rewroteAny = False
for header in m.headers:
for idx, _name, other in header.walkRelocatables():
data = rewrite_map.get(other)
if data:
if header.rewriteDataForCommand(
idx, data.encode(sys.getfilesystemencoding())
):
rewroteAny = True
if rewroteAny:
old_mode = flipwritable(m.filename)
try:
with open(m.filename, "rb+") as f:
for header in m.headers:
f.seek(0)
header.write(f)
f.seek(0, 2)
f.flush()
finally:
flipwritable(m.filename, old_mode)
else:
print("_tkinter already linked against system Tcl/Tk")
def get_zipfile(dist, semi_standalone=False):
if sys.version_info[0] == 3:
if semi_standalone:
return "python%d.%d/site-packages.zip" % (sys.version_info[:2])
else:
return "python%d%d.zip" % (sys.version_info[:2])
return getattr(dist, "zipfile", None) or "site-packages.zip"
def framework_copy_condition(src):
# Skip Headers, .svn, and CVS dirs
return skipscm(src) and os.path.basename(src) != "Headers"
class PythonStandalone(macholib.MachOStandalone.MachOStandalone):
def __init__(self, appbuilder, ext_dir, copyexts, *args, **kwargs):
super(PythonStandalone, self).__init__(*args, **kwargs)
self.appbuilder = appbuilder
self.ext_map = {}
for e in copyexts:
fn = os.path.join(
ext_dir,
(e.identifier.replace(".", os.sep) + os.path.splitext(e.filename)[1]),
)
self.ext_map[fn] = os.path.dirname(e.filename)
def update_node(self, m):
if isinstance(m, macholib.MachO.MachO):
if m.filename in self.ext_map:
m.loader_path = self.ext_map[m.filename]
return m
def copy_dylib(self, src):
dest = os.path.join(self.dest, os.path.basename(src))
if os.path.islink(src):
dest = os.path.join(self.dest, os.path.basename(os.path.realpath(src)))
# Ensure that the orginal name also exists, avoids problems when
# the filename is used from Python (see issue #65)
#
# NOTE: The if statement checks that the target link won't
# point to itself, needed for systems like homebrew that
# store symlinks in "public" locations that point to
# files of the same name in a per-package install location.
link_dest = os.path.join(self.dest, os.path.basename(src))
if os.path.basename(link_dest) != os.path.basename(dest):
make_symlink(os.path.basename(dest), link_dest)
else:
dest = os.path.join(self.dest, os.path.basename(src))
self.ext_map[dest] = os.path.dirname(src)
return self.appbuilder.copy_dylib(src, dest)
def copy_framework(self, info):
destfn = self.appbuilder.copy_framework(info, self.dest)
dest = os.path.join(self.dest, info["shortname"] + ".framework")
self.pending.append((destfn, iter_platform_files(dest)))
return destfn
def iterRecipes(module=recipes):
for name in dir(module):
if name.startswith("_"):
continue
check = getattr(getattr(module, name), "check", None)
if check is not None:
yield (name, check)
# A very loosely defined "target". We assume either a "script" or "modules"
# attribute. Some attributes will be target specific.
class Target(object):
def __init__(self, **kw):
self.__dict__.update(kw)
# If modules is a simple string, assume they meant list
m = self.__dict__.get("modules")
if m and isinstance(m, basestring):
self.modules = [m]
def __repr__(self):
return "<Target %s>"%(self.__dict__,)
def get_dest_base(self):
dest_base = getattr(self, "dest_base", None)
if dest_base:
return dest_base
script = getattr(self, "script", None)
if script:
return os.path.basename(os.path.splitext(script)[0])
modules = getattr(self, "modules", None)
assert modules, "no script, modules or dest_base specified"
return modules[0].split(".")[-1]
def validate(self):
resources = getattr(self, "resources", [])
for r_filename in resources:
if not os.path.isfile(r_filename):
raise DistutilsOptionError(
"Resource filename '%s' does not exist" % (r_filename,)
)
def validate_target(dist, attr, value):
res = FixupTargets(value, "script")
other = {"app": "plugin", "plugin": "app"}
if res and getattr(dist, other[attr]):
raise DistutilsOptionError("You must specify either app or plugin, not both")
def FixupTargets(targets, default_attribute):
if not targets:
return targets
try:
targets = eval(targets)
except: # noqa: E722,B001
pass
ret = []
for target_def in targets:
if isinstance(target_def, basestring):
# Create a default target object, with the string as the attribute
target = Target(**{default_attribute: target_def})
else:
d = getattr(target_def, "__dict__", target_def)
if default_attribute not in d:
raise DistutilsOptionError(
"This target class requires an attribute '%s'"
% (default_attribute,)
)
target = Target(**d)
target.validate()
ret.append(target)
return ret
def normalize_data_file(fn):
if isinstance(fn, basestring):
fn = convert_path(fn)
return ("", [fn])
return fn
def is_system():
prefix = sys.prefix
if os.path.exists(os.path.join(prefix, ".Python")):
fn = os.path.join(
prefix, "lib", "python%d.%d" % (sys.version_info[:2]), "orig-prefix.txt"
)
if os.path.exists(fn):
with open(fn, "rU") as fp:
prefix = fp.read().strip()
return in_system_path(prefix)
def installation_info(version=None):
if version is None:
version = sys.version
if is_system():
return ".".join(version.split(".")[:2]) + " (FORCED: Using vendor Python)"
else:
return ".".join(version.split(".")[:2])
class py2app(Command):
description = "create a Mac OS X application or plugin from Python scripts"
# List of option tuples: long name, short name (None if no short
# name), and help string.
user_options = [
("app=", None, "application bundle to be built"),
("plugin=", None, "plugin bundle to be built"),
(
"optimize=",
"O",
'optimization level: -O1 for "python -O", '
'-O2 for "python -OO", and -O0 to disable [default: -O0]',
),
("includes=", "i", "comma-separated list of modules to include"),
("packages=", "p", "comma-separated list of packages to include"),
("iconfile=", None, "Icon file to use"),
("excludes=", "e", "comma-separated list of modules to exclude"),
(
"dylib-excludes=",
"E",
"comma-separated list of frameworks or dylibs to exclude",
),
("datamodels=", None, "xcdatamodels to be compiled and copied into Resources"),
(
"expected-missing-imports=",
None,
"expected missing imports either a comma sperated list "
"or @ followed by file containing a list of imports, one per line",
),
(
"mappingmodels=",
None,
"xcmappingmodels to be compiled and copied into Resources",
),
(
"resources=",
"r",
"comma-separated list of additional data files and folders to "
"include (not for code!)",
),
(
"frameworks=",
"f",
"comma-separated list of additional frameworks and dylibs to " "include",
),
("plist=", "P", "Info.plist template file, dict, or plistlib.Plist"),
(
"extension=",
None,
"Bundle extension [default:.app for app, .plugin for plugin]",
),
("graph", "g", "output module dependency graph"),
("xref", "x", "output module cross-reference as html"),
("no-strip", None, "do not strip debug and local symbols from output"),
# ("compressed", 'c',
# "create a compressed zipfile"),
(
"no-chdir",
"C",
"do not change to the data directory (Contents/Resources) "
"[forced for plugins]",
),
# ("no-zip", 'Z',
# "do not use a zip file"),
(
"semi-standalone",
"s",
"depend on an existing installation of Python " + installation_info(),
),
("alias", "A", "Use an alias to current source file (for development only!)"),
("argv-emulation", "a", "Use argv emulation [disabled for plugins]."),
("argv-inject=", None, "Inject some commands into the argv"),
(
"emulate-shell-environment",
None,
"Emulate the shell environment you get in a Terminal window",
),
(
"use-pythonpath",
None,
"Allow PYTHONPATH to effect the interpreter's environment",
),
(
"use-faulthandler",
None,
"Enable the faulthandler in the generated bundle (Python 3.3+)",
),
("verbose-interpreter", None, "Start python in verbose mode"),
("bdist-base=", "b", "base directory for build library (default is build)"),
(
"dist-dir=",
"d",
"directory to put final built distributions in (default is dist)",
),
(
"site-packages",
None,
"include the system and user site-packages into sys.path",
),
(
"strip",
"S",
"strip debug and local symbols from output (on by default, for "
"compatibility)",
),
(
"prefer-ppc",
None,
"Force application to run translated on i386 (LSPrefersPPC=True)",
),
(
"debug-modulegraph",
None,
"Drop to pdb console after the module finding phase is complete",
),
(
"debug-skip-macholib",
None,
"skip macholib phase (app will not be standalone!)",
),
(
"arch=",
None,
"set of architectures to use (fat, fat3, universal, intel, "
"i386, ppc, x86_64; default is the set for the current python "
"binary)",
),
(
"qt-plugins=",
None,
"set of Qt plugins to include in the application bundle " "(default None)",
),
(
"matplotlib-backends=",
None,
"set of matplotlib backends to include (default: all)",
),
(
"extra-scripts=",
None,
"set of additonal scripts to include in the application bundle",
),
("include-plugins=", None, "List of plugins to include"),
(
"force-system-tk",
None,
"Ensure that Tkinter is linked against Apple's build of Tcl/Tk",
),
(
"report-missing-from-imports",
None,
"Report the list of missing names for 'from module import name'",
),
(
"no-report-missing-conditional-import",
None,
"Don't report missing modules from conditional imports",
),
(
"redirect-stdout-to-asl",
None,
"Forward the stdout/stderr streams to Console.app using ASL",
),
]
boolean_options = [
# "compressed",
"xref",
"strip",
"no-strip",
"site-packages",
"semi-standalone",
"alias",
"argv-emulation",
# "no-zip",
"use-pythonpath",
"use-faulthandler",
"verbose-interpreter",
"no-chdir",
"debug-modulegraph",
"debug-skip-macholib",
"graph",
"prefer-ppc",
"emulate-shell-environment",
"force-system-tk",
"report-missing-from-imports",
"no-report-missing-conditional-import",
"redirect-stdout-to-asl",
]
always_expected_missing_imports = {
"org",
"java", # Jython only
"_frozen_importlib_external", # Seems to be side effect of py2app
}
def initialize_options(self):
self.app = None
self.plugin = None
self.bdist_base = None
self.xref = False
self.graph = False
self.no_zip = 0
self.optimize = None
# self.optimize = 0
# if hasattr(sys, 'flags'):
# self.optimize = sys.flags.optimize
self.arch = None
self.strip = True
self.no_strip = False
self.iconfile = None
self.extension = None
self.alias = 0
self.argv_emulation = 0
self.emulate_shell_environment = 0
self.argv_inject = None
self.no_chdir = 0
self.site_packages = False
self.use_pythonpath = False
self.use_faulthandler = False
self.verbose_interpreter = False
self.includes = None
self.packages = None
self.excludes = None
self.dylib_excludes = None
self.frameworks = None
self.resources = None
self.datamodels = None
self.mappingmodels = None
self.plist = None
self.compressed = True
self.semi_standalone = is_system()
self.dist_dir = None
self.debug_skip_macholib = False
self.debug_modulegraph = False
self.prefer_ppc = False
self.filters = []
self.eggs = []
self.qt_plugins = None
self.matplotlib_backends = None
self.extra_scripts = None
self.include_plugins = None
self.force_system_tk = False
self.report_missing_from_imports = False
self.no_report_missing_conditional_import = False
self.redirect_stdout_to_asl = False
self._python_app = None
self.use_old_sdk = False
self.expected_missing_imports = None
def finalize_options(self):
if self.prefer_ppc:
print(
"WARNING: Option --prefer-ppc is deprecated an will be removed "
"in a future version. Use --arch instead"
)
if sys_base_prefix != sys.prefix:
self._python_app = os.path.join(sys_base_prefix, "Resources", "Python.app")
elif os.path.exists(os.path.join(sys.prefix, "pyvenv.cfg")):
with open(os.path.join(sys.prefix, "pyvenv.cfg")) as fp:
for line in fp:
if line.startswith("home = "):
_, home_path = line.split("=", 1)
prefix = os.path.dirname(home_path.strip())
break
else:
raise DistutilsPlatformError(
"Pyvenv detected, but cannot determine base prefix"
)
self._python_app = os.path.join(prefix, "Resources", "Python.app")
elif os.path.exists(os.path.join(sys.prefix, ".Python")):
fn = os.path.join(
sys.prefix,
"lib",
"python%d.%d" % (sys.version_info[:2]),
"orig-prefix.txt",
)
if os.path.exists(fn):
with open(fn, "rU") as fp:
prefix = fp.read().strip()
self._python_app = os.path.join(prefix, "Resources", "Python.app")
else:
raise DistutilsPlatformError(
"Virtualenv detected, but cannot determine base prefix"
)
else:
self._python_app = os.path.join(sys.prefix, "Resources", "Python.app")
if self.optimize is None:
self.optimize = 0
if hasattr(sys, "flags"):
self.optimize = sys.flags.optimize
if not self.strip:
self.no_strip = True
elif self.no_strip:
self.strip = False
self.optimize = int(self.optimize)
if self.argv_inject and isinstance(self.argv_inject, basestring):
self.argv_inject = shlex.split(self.argv_inject)
self.includes = set(fancy_split(self.includes))
self.includes.add("encodings.*")
self.includes.add("_sitebuiltins")
if self.use_faulthandler:
self.includes.add("faulthandler")
self.packages = set(fancy_split(self.packages))
self.excludes = set(fancy_split(self.excludes))
self.excludes.add("readline")
# included by apptemplate
self.excludes.add("site")
if getattr(self.distribution, "install_requires", None):
self.includes.add("pkg_resources")
self.eggs = pkg_resources.require(self.distribution.install_requires)
# Setuptools/distribute style namespace packages uses
# __import__('pkg_resources'), and that import isn't detected at the
# moment. Forcefully include pkg_resources.
self.includes.add("pkg_resources")
dylib_excludes = fancy_split(self.dylib_excludes)
self.dylib_excludes = []
for fn in dylib_excludes:
try:
res = macholib.dyld.framework_find(fn)
except ValueError:
try:
res = macholib.dyld.dyld_find(fn)
except ValueError:
res = fn
self.dylib_excludes.append(res)
self.resources = fancy_split(self.resources)
frameworks = fancy_split(self.frameworks)
self.frameworks = []
for fn in frameworks:
try:
res = macholib.dyld.framework_find(fn)
except ValueError:
res = macholib.dyld.dyld_find(fn)
while res in self.dylib_excludes:
self.dylib_excludes.remove(res)
self.frameworks.append(res)
if not self.plist:
self.plist = {}
if isinstance(self.plist, basestring):
if hasattr(plistlib, "load"):
with open(self.plist, "rb") as fp:
self.plist = plistlib.load(fp)
else:
# 2.7
self.plist = plistlib.Plist.fromFile(self.plist)
if hasattr(plistlib, "Dict") and isinstance(self.plist, plistlib.Dict):
# 2.7
self.plist = dict(self.plist.__dict__)
else:
self.plist = dict(self.plist)
self.set_undefined_options(
"bdist", ("dist_dir", "dist_dir"), ("bdist_base", "bdist_base")
)
if self.semi_standalone:
self.filters.append(not_stdlib_filter)
if self.iconfile is None and "CFBundleIconFile" not in self.plist:
# Default is the generic applet icon in the framework
iconfile = os.path.join(
self._python_app, "Contents", "Resources", "PythonApplet.icns"
)
if os.path.exists(iconfile):
self.iconfile = iconfile
self.runtime_preferences = list(self.get_runtime_preferences())
self.qt_plugins = fancy_split(self.qt_plugins)
self.matplotlib_backends = fancy_split(self.matplotlib_backends)
self.extra_scripts = fancy_split(self.extra_scripts)
self.include_plugins = fancy_split(self.include_plugins)
if self.expected_missing_imports is None:
self.expected_missing_imports = self.always_expected_missing_imports
else:
if self.expected_missing_imports.startswith("@"):
self.expected_missing_imports = self.read_expected_missing_imports_file(
self.expected_missing_imports[1:]
)
else:
self.expected_missing_imports = set(
fancy_split(self.expected_missing_imports)
)
self.expected_missing_imports |= self.always_expected_missing_imports
if self.datamodels:
print(
"WARNING: the datamodels option is deprecated, "
"add model files to the list of resources"
)
if self.mappingmodels:
print(
"WARNING: the mappingmodels option is deprecated, "
"add model files to the list of resources"
)
def read_expected_missing_imports_file(self, filename):
#
# ignore blank lines and lines that start with a '#'
# only one import per line
#
expected_missing_imports = set()
with open(filename, "r") as f:
for line in f:
line = line.strip()
if line.startswith("#") or line == "":
continue
expected_missing_imports.add(line)
return expected_missing_imports
def get_default_plist(self):
plist = {}
target = self.targets[0]
version = self.distribution.get_version()
if version == "0.0.0":
try:
version = find_version(target.script)
except ValueError:
pass
if not isinstance(version, basestring):
raise DistutilsOptionError("Version must be a string")
if sys.version_info[0] > 2 and isinstance(version, type("a".encode("ascii"))):
raise DistutilsOptionError("Version must be a string")
plist["CFBundleVersion"] = version
name = self.distribution.get_name()
if name == "UNKNOWN":
base = target.get_dest_base()
name = os.path.basename(base)
plist["CFBundleName"] = name
return plist
def get_runtime(self, prefix=None, version=None):
# this is a bit of a hack!
# ideally we'd use dylib functions to figure this out
if prefix is None:
prefix = sys.prefix
if version is None:
version = sys.version
version = ".".join(version.split(".")[:2])
info = None
if sys_base_prefix != sys.prefix:
prefix = sys_base_prefix
elif os.path.exists(os.path.join(prefix, "pyvenv.cfg")):
with open(os.path.join(prefix, "pyvenv.cfg")) as fp:
for ln in fp:
if ln.startswith("home = "):
_, home_path = ln.split("=", 1)
prefix = os.path.dirname(home_path.strip())
break
else:
raise DistutilsPlatformError(
"Pyvenv detected, cannot determine base prefix"
)
elif os.path.exists(os.path.join(prefix, ".Python")):
# We're in a virtualenv environment, locate the real prefix
fn = os.path.join(
prefix, "lib", "python%d.%d" % (sys.version_info[:2]), "orig-prefix.txt"
)
if os.path.exists(fn):
with open(fn, "rU") as fp:
prefix = fp.read().strip()
try:
fmwk = macholib.dyld.framework_find(prefix)
except ValueError:
info = None
else:
info = macholib.dyld.framework_info(fmwk)
if info is not None:
dylib = info["name"]
runtime = os.path.join(info["location"], info["name"])
else:
dylib = "libpython%d.%d.dylib" % (sys.version_info[:2])
runtime = os.path.join(prefix, "lib", dylib)
return dylib, runtime
def get_runtime_preferences(self, prefix=None, version=None):
dylib, runtime = self.get_runtime(prefix=prefix, version=version)
yield os.path.join("@executable_path", "..", "Frameworks", dylib)
if self.semi_standalone or self.alias:
yield runtime
def run(self):
if get_config_var("PYTHONFRAMEWORK") is None:
if not get_config_var("Py_ENABLE_SHARED"):
raise DistutilsPlatformError(
"This python does not have a shared library or framework"
)
else:
# Issue .. in py2app's tracker, and issue .. in python's
# tracker: a unix-style shared library build did not read the
# application environment correctly. The collection of
# if statements below gives a clean error message when py2app
# is started, instead of building a bundle that will give a
# confusing error message when started.
msg = (
"py2app is not supported for a shared library build "
"with this version of python"
)
if sys.version_info[:2] < (2, 7):
raise DistutilsPlatformError(msg)
elif sys.version_info[:2] == (2, 7) and sys.version_info[3] < 4:
raise DistutilsPlatformError(msg)
elif sys.version_info[0] == 3 and sys.version_info[1] < 2:
raise DistutilsPlatformError(msg)
elif sys.version_info[:2] == (3, 2) and sys.version_info[3] < 3:
raise DistutilsPlatformError(msg)
elif sys.version_info[:2] == (3, 3) and sys.version_info[3] < 1:
raise DistutilsPlatformError(msg)
if (
hasattr(self.distribution, "install_requires")
and self.distribution.install_requires
):
self.distribution.fetch_build_eggs(self.distribution.install_requires)
build = self.reinitialize_command("build")
build.build_base = self.bdist_base
build.run()
self.create_directories()
self.fixup_distribution()
self.initialize_plist()
sys_old_path = sys.path[:]
extra_paths = [os.path.dirname(target.script) for target in self.targets]
extra_paths.extend([build.build_platlib, build.build_lib])
self.additional_paths = [
os.path.abspath(p) for p in extra_paths if p is not None
]
sys.path[:0] = self.additional_paths
# this needs additional_paths
self.initialize_prescripts()
try:
self._run()
finally:
sys.path = sys_old_path
def iter_datamodels(self, resdir):
for (path, files) in (
normalize_data_file(fn) for fn in (self.datamodels or ())
):
path = fsencoding(path)
for fn in files:
fn = fsencoding(fn)
basefn, ext = os.path.splitext(fn)
if ext != ".xcdatamodel":
basefn = fn
fn += ".xcdatamodel"
destfn = os.path.basename(basefn) + ".mom"
yield fn, os.path.join(resdir, path, destfn)
def compile_datamodels(self, resdir):
for src, dest in self.iter_datamodels(resdir):
print("compile datamodel", src, "->", dest)
self.mkpath(os.path.dirname(dest))
momc(src, dest)
def iter_mappingmodels(self, resdir):
for (path, files) in (
normalize_data_file(fn) for fn in (self.mappingmodels or ())
):
path = fsencoding(path)
for fn in files:
fn = fsencoding(fn)
basefn, ext = os.path.splitext(fn)
if ext != ".xcmappingmodel":
basefn = fn
fn += ".xcmappingmodel"
destfn = os.path.basename(basefn) + ".cdm"
yield fn, os.path.join(resdir, path, destfn)