-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuild.py
executable file
·1496 lines (1361 loc) · 57.2 KB
/
Build.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
#!/usr/bin/env python
#
# Build packages using spec files
#
# Copyright (C) 2005, Giovanni Bajo
# Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
import sys
import os
import shutil
import pprint
import time
import py_compile
import tempfile
try:
from hashlib import md5
except ImportError:
from md5 import new as md5
import UserList
import mf
import archive
import iu
import carchive
import bindepend
import traceback
STRINGTYPE = type('')
TUPLETYPE = type((None,))
UNCOMPRESSED, COMPRESSED = range(2)
# todo: use pkg_resources here
HOMEPATH = os.path.dirname(sys.argv[0])
SPEC = None
SPECPATH = None
BUILDPATH = None
WARNFILE = None
rthooks = {}
iswin = sys.platform[:3] == 'win'
cygwin = sys.platform == 'cygwin'
def system(cmd):
# This workaround is required because NT shell doesn't work with commands
# that start with double quotes (required if there are spaces inside the
# command path)
if iswin:
cmd = 'echo on && ' + cmd
os.system(cmd)
def _save_data(filename, data):
outf = open(filename, 'w')
pprint.pprint(data, outf)
outf.close()
def _load_data(filename):
return eval(open(filename, 'r').read().replace("\r\n","\n"))
def setupUPXFlags():
f = os.environ.get("UPX", "")
is24 = hasattr(sys, "version_info") and sys.version_info[:2] >= (2,4)
if iswin and is24:
# Binaries built with Visual Studio 7.1 require --strip-loadconf
# or they won't compress. Configure.py makes sure that UPX is new
# enough to support --strip-loadconf.
f = "--strip-loadconf " + f
# Do not compress any icon, so that additional icons in the executable
# can still be externally bound
f = "--compress-icons=0 " + f
f = "--best " + f
os.environ["UPX"] = f
def mtime(fnm):
try:
return os.stat(fnm)[8]
except:
return 0
def absnormpath(apath):
return os.path.abspath(os.path.normpath(apath))
def compile_pycos(toc):
"""Given a TOC or equivalent list of tuples, generates all the required
pyc/pyo files, writing in a local directory if required, and returns the
list of tuples with the updated pathnames.
"""
global BUILDPATH
# For those modules that need to be rebuilt, use the build directory
# PyInstaller creates during the build process.
basepath = "/".join([BUILDPATH, "localpycos"])
new_toc = []
for (nm, fnm, typ) in toc:
# Trim the terminal "c" or "o"
source_fnm = fnm[:-1]
# If the source is newer than the compiled, or the compiled doesn't
# exist, we need to perform a build ourselves.
if mtime(source_fnm) > mtime(fnm):
try:
py_compile.compile(source_fnm)
except IOError:
# If we're compiling on a system directory, probably we don't
# have write permissions; thus we compile to a local directory
# and change the TOC entry accordingly.
ext = os.path.splitext(fnm)[1]
if "__init__" not in fnm:
# If it's a normal module, use last part of the qualified
# name as module name and the first as leading path
leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1]
else:
# In case of a __init__ module, use all the qualified name
# as leading path and use "__init__" as the module name
leading, mod_name = nm.split("."), "__init__"
leading.insert(0, basepath)
leading = "/".join(leading)
if not os.path.exists(leading):
os.makedirs(leading)
fnm = "/".join([leading, mod_name + ext])
py_compile.compile(source_fnm, fnm)
new_toc.append((nm, fnm, typ))
return new_toc
def addSuffixToExtensions(toc):
"""
Returns a new TOC with proper library suffix for EXTENSION items.
"""
new_toc = TOC()
for inm, fnm, typ in toc:
if typ == 'EXTENSION':
binext = os.path.splitext(fnm)[1]
if not os.path.splitext(inm)[1] == binext:
inm = inm + binext
new_toc.append((inm, fnm, typ))
return new_toc
def architecture():
"""
Returns the bit depth of the python interpreter's architecture as
a string ('32bit' or '64bit'). Similar to platform.architecture(),
but with fixes for universal binaries on MacOS.
"""
if sys.platform == "darwin":
# Darwin's platform.architecture() is buggy and always
# returns "64bit" even for the 32bit version of Python's
# universal binary. So we roll out our own (that works
# on Darwin).
if sys.maxint > 2L**32:
return '64bit'
else:
return '32bit'
# Python 2.3+
import platform
return platform.architecture()[0]
#--- functons for checking guts ---
def _check_guts_eq(attr, old, new, last_build):
"""
rebuild is required if values differ
"""
if old != new:
print "building because %s changed" % attr
return True
return False
def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if mtimes of files listed in old toc are newer
than ast_build
if pyc=1, check for .py files, too
"""
for (nm, fnm, typ) in old:
if mtime(fnm) > last_build:
print "building because %s changed" % fnm
return True
elif pyc and mtime(fnm[:-1]) > last_build:
print "building because %s changed" % fnm[:-1]
return True
return False
def _check_guts_toc(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if either toc content changed if mtimes of
files listed in old toc are newer than ast_build
if pyc=1, check for .py files, too
"""
return _check_guts_eq (attr, old, toc, last_build) \
or _check_guts_toc_mtime(attr, old, toc, last_build, pyc=pyc)
def _rmdir(path):
"""
Remove dirname(os.path.abspath(path)) and all its contents, but only if:
1. It doesn't start with BUILDPATH
2. It is a directory and not empty (otherwise continue without removing
the directory)
3. BUILDPATH and SPECPATH don't start with it
4. The --noconfirm option is set, or sys.stdout is a tty and the user
confirms directory removal
Otherwise, error out.
"""
if not os.path.abspath(path):
path = os.path.abspath(path)
if not path.startswith(BUILDPATH) and os.path.isdir(path) and os.listdir(path):
specerr = 0
if BUILDPATH.startswith(path):
print ('E: specfile error: The output path "%s" contains '
'BUILDPATH (%s)') % (path, BUILDPATH)
specerr += 1
if SPECPATH.startswith(path):
print ('E: Specfile error: The output path "%s" contains '
'SPECPATH (%s)') % (path, SPECPATH)
specerr += 1
if specerr:
print ('Please edit/recreate the specfile (%s), set a different '
'output name (e.g. "dist") and run Build.py again.') % SPEC
sys.exit(1)
if opts.noconfirm:
choice = 'y'
elif sys.stdout.isatty():
choice = raw_input('WARNING: The output directory "%s" and ALL ITS '
'CONTENTS will be REMOVED! Continue? (y/n)' % path)
else:
print ('E: The output directory "%s" is not empty. Please remove '
'all its contents and run Build.py again, or use Build.py '
'-y (remove output directory without confirmation).') % path
sys.exit(1)
if choice.strip().lower() == 'y':
print 'I: Removing', path
shutil.rmtree(path)
else:
print 'I: User aborted'
sys.exit(1)
def check_egg(pth):
"""Check if path points to a file inside a python egg file (or to an egg
directly)."""
if sys.version_info >= (2,3):
if os.path.altsep:
pth = pth.replace(os.path.altsep, os.path.sep)
components = pth.split(os.path.sep)
sep = os.path.sep
else:
components = pth.replace("\\", "/").split("/")
sep = "/"
if iswin:
sep = "\\"
for i,name in zip(range(0,len(components)), components):
if name.lower().endswith(".egg"):
eggpth = sep.join(components[:i + 1])
if os.path.isfile(eggpth):
# eggs can also be directories!
return True
return False
#--
class Target:
invcnum = 0
def __init__(self):
self.invcnum = Target.invcnum
Target.invcnum += 1
self.out = os.path.join(BUILDPATH, 'out%s%d.toc' % (self.__class__.__name__,
self.invcnum))
self.outnm = os.path.basename(self.out)
self.dependencies = TOC()
def __postinit__(self):
print "checking %s" % (self.__class__.__name__,)
if self.check_guts(mtime(self.out)):
self.assemble()
GUTS = []
def check_guts(self, last_build):
pass
def get_guts(self, last_build, missing ='missing or bad'):
"""
returns None if guts have changed
"""
try:
data = _load_data(self.out)
except:
print "building because", os.path.basename(self.out), missing
return None
if len(data) != len(self.GUTS):
print "building because %s is bad" % self.outnm
return None
for i in range(len(self.GUTS)):
attr, func = self.GUTS[i]
if func is None:
# no check for this value
continue
if func(attr, data[i], getattr(self, attr), last_build):
return None
return data
class Analysis(Target):
def __init__(self, scripts=None, pathex=None, hookspath=None, excludes=None):
Target.__init__(self)
self.inputs = scripts
for script in scripts:
if not os.path.exists(script):
raise ValueError, "script '%s' not found" % script
self.pathex = []
if pathex:
for path in pathex:
self.pathex.append(absnormpath(path))
sys.pathex = self.pathex[:]
self.hookspath = hookspath
self.excludes = excludes
self.scripts = TOC()
self.pure = TOC()
self.binaries = TOC()
self.zipfiles = TOC()
self.datas = TOC()
self.__postinit__()
GUTS = (('inputs', _check_guts_eq),
('pathex', _check_guts_eq),
('hookspath', _check_guts_eq),
('excludes', _check_guts_eq),
('scripts', _check_guts_toc_mtime),
('pure', lambda *args: apply(_check_guts_toc_mtime,
args, {'pyc': 1 } )),
('binaries', _check_guts_toc_mtime),
('zipfiles', _check_guts_toc_mtime),
('datas', _check_guts_toc_mtime),
)
def check_guts(self, last_build):
if last_build == 0:
print "building %s because %s non existent" % (self.__class__.__name__, self.outnm)
return True
for fnm in self.inputs:
if mtime(fnm) > last_build:
print "building because %s changed" % fnm
return True
data = Target.get_guts(self, last_build)
if not data:
return True
scripts, pure, binaries, zipfiles, datas = data[-5:]
self.scripts = TOC(scripts)
self.pure = TOC(pure)
self.binaries = TOC(binaries)
self.zipfiles = TOC(zipfiles)
self.datas = TOC(datas)
return False
def assemble(self):
print "running Analysis", os.path.basename(self.out)
# Reset seen variable to correctly discover dependencies
# if there are multiple Analysis in a single specfile.
bindepend.seen = {}
paths = self.pathex
for i in range(len(paths)):
# FIXME: isn't self.pathex already norm-abs-pathed?
paths[i] = absnormpath(paths[i])
###################################################
# Scan inputs and prepare:
dirs = {} # input directories
pynms = [] # python filenames with no extension
for script in self.inputs:
if not os.path.exists(script):
print "Analysis: script %s not found!" % script
sys.exit(1)
d, base = os.path.split(script)
if not d:
d = os.getcwd()
d = absnormpath(d)
pynm, ext = os.path.splitext(base)
dirs[d] = 1
pynms.append(pynm)
###################################################
# Initialize analyzer and analyze scripts
analyzer = mf.ImportTracker(dirs.keys()+paths, self.hookspath,
self.excludes,
target_platform=target_platform)
#print analyzer.path
scripts = [] # will contain scripts to bundle
for i in range(len(self.inputs)):
script = self.inputs[i]
print "Analyzing:", script
analyzer.analyze_script(script)
scripts.append((pynms[i], script, 'PYSOURCE'))
###################################################
# Fills pure, binaries and rthookcs lists to TOC
pure = [] # pure python modules
binaries = [] # binaries to bundle
zipfiles = [] # zipfiles to bundle
datas = [] # datafiles to bundle
rthooks = [] # rthooks if needed
for modnm, mod in analyzer.modules.items():
# FIXME: why can we have a mod == None here?
if mod is not None:
hooks = findRTHook(modnm) #XXX
if hooks:
rthooks.extend(hooks)
datas.extend(mod.datas)
if isinstance(mod, mf.BuiltinModule):
pass
else:
fnm = mod.__file__
if isinstance(mod, mf.ExtensionModule):
binaries.append((mod.__name__, fnm, 'EXTENSION'))
elif isinstance(mod, (mf.PkgInZipModule, mf.PyInZipModule)):
zipfiles.append(("eggs/" + os.path.basename(str(mod.owner)),
str(mod.owner), 'ZIPFILE'))
else:
# mf.PyModule instances expose a list of binary
# dependencies, most probably shared libraries accessed
# via ctypes. Add them to the overall required binaries.
binaries.extend(mod.binaries)
if modnm != '__main__':
pure.append((modnm, fnm, 'PYMODULE'))
# Always add python's dependencies first
# This ensures that assembly depencies under Windows get pulled in
# first and we do not need to add assembly DLLs to the exclude list
# explicitly
python = config['python']
if not iswin:
while os.path.islink(python):
python = os.path.join(os.path.split(python)[0], os.readlink(python))
depmanifest = None
else:
depmanifest = winmanifest.Manifest(type_="win32", name=specnm,
processorArchitecture="x86",
version=(1, 0, 0, 0))
depmanifest.filename = os.path.join(BUILDPATH,
specnm + ".exe.manifest")
binaries.extend(bindepend.Dependencies([('', python, '')],
target_platform,
config['xtrapath'],
manifest=depmanifest)[1:])
binaries.extend(bindepend.Dependencies(binaries,
platform=target_platform,
manifest=depmanifest))
if iswin:
depmanifest.writeprettyxml()
self.fixMissingPythonLib(binaries)
if zipfiles:
scripts[-1:-1] = [("_pyi_egg_install.py", os.path.join(HOMEPATH, "support/_pyi_egg_install.py"), 'PYSOURCE')]
# Add realtime hooks just before the last script (which is
# the entrypoint of the application).
scripts[-1:-1] = rthooks
self.scripts = TOC(scripts)
self.pure = TOC(pure)
self.binaries = TOC(binaries)
self.zipfiles = TOC(zipfiles)
self.datas = TOC(datas)
try: # read .toc
oldstuff = _load_data(self.out)
except:
oldstuff = None
self.pure = TOC(compile_pycos(self.pure))
newstuff = (self.inputs, self.pathex, self.hookspath, self.excludes,
self.scripts, self.pure, self.binaries, self.zipfiles, self.datas)
if oldstuff != newstuff:
_save_data(self.out, newstuff)
wf = open(WARNFILE, 'w')
for ln in analyzer.getwarnings():
wf.write(ln+'\n')
wf.close()
print "Warnings written to %s" % WARNFILE
return 1
print self.out, "no change!"
return 0
def fixMissingPythonLib(self, binaries):
"""Add the Python library if missing from the binaries.
Some linux distributions (e.g. debian-based) statically build the
Python executable to the libpython, so bindepend doesn't include
it in its output.
Darwin custom builds could possibly also have non-framework style libraries,
so this method also checks for that variant as well.
"""
if target_platform.startswith("linux"):
names = ('libpython%d.%d.so' % sys.version_info[:2],)
elif target_platform.startswith("darwin"):
names = ('Python', 'libpython%d.%d.dylib' % sys.version_info[:2])
else:
return
for (nm, fnm, typ) in binaries:
for name in names:
if typ == 'BINARY' and name in fnm:
# lib found
return
# resume search using the first item in names
name = names[0]
if target_platform.startswith("linux"):
lib = bindepend.findLibrary(name)
if lib is None:
raise IOError("Python library not found!")
elif target_platform.startswith("darwin"):
# On MacPython, Analysis.assemble is able to find the libpython with
# no additional help, asking for config['python'] dependencies.
# However, this fails on system python, because the shared library
# is not listed as a dependency of the binary (most probably it's
# opened at runtime using some dlopen trickery).
lib = os.path.join(sys.exec_prefix, 'Python')
if not os.path.exists(lib):
raise IOError("Python library not found!")
binaries.append((os.path.split(lib)[1], lib, 'BINARY'))
def findRTHook(modnm):
hooklist = rthooks.get(modnm)
if hooklist:
rslt = []
for script in hooklist:
nm = os.path.basename(script)
nm = os.path.splitext(nm)[0]
if os.path.isabs(script):
path = script
else:
path = os.path.join(HOMEPATH, script)
rslt.append((nm, path, 'PYSOURCE'))
return rslt
return None
class PYZ(Target):
typ = 'PYZ'
def __init__(self, toc, name=None, level=9, crypt=None):
Target.__init__(self)
self.toc = toc
self.name = name
if name is None:
self.name = self.out[:-3] + 'pyz'
if config['useZLIB']:
self.level = level
else:
self.level = 0
if config['useCrypt'] and crypt is not None:
self.crypt = archive.Keyfile(crypt).key
else:
self.crypt = None
self.dependencies = compile_pycos(config['PYZ_dependencies'])
self.__postinit__()
GUTS = (('name', _check_guts_eq),
('level', _check_guts_eq),
('crypt', _check_guts_eq),
('toc', _check_guts_toc), # todo: pyc=1
)
def check_guts(self, last_build):
_rmdir(self.name)
if not os.path.exists(self.name):
print "rebuilding %s because %s is missing" % (self.outnm, os.path.basename(self.name))
return True
data = Target.get_guts(self, last_build)
if not data:
return True
return False
def assemble(self):
print "building PYZ", os.path.basename(self.out)
pyz = archive.ZlibArchive(level=self.level, crypt=self.crypt)
toc = self.toc - config['PYZ_dependencies']
pyz.build(self.name, toc)
_save_data(self.out, (self.name, self.level, self.crypt, self.toc))
return 1
def cacheDigest(fnm):
data = open(fnm, "rb").read()
digest = md5(data).digest()
return digest
def checkCache(fnm, strip, upx):
# On darwin a cache is required anyway to keep the libaries
# with relative install names
if (not strip and not upx and sys.platform[:6] != 'darwin' and
sys.platform != 'win32') or fnm.lower().endswith(".manifest"):
return fnm
if strip:
strip = 1
else:
strip = 0
if upx:
upx = 1
else:
upx = 0
# Load cache index
cachedir = os.path.join(HOMEPATH, 'bincache%d%d' % (strip, upx))
if not os.path.exists(cachedir):
os.makedirs(cachedir)
cacheindexfn = os.path.join(cachedir, "index.dat")
if os.path.exists(cacheindexfn):
cache_index = _load_data(cacheindexfn)
else:
cache_index = {}
# Verify if the file we're looking for is present in the cache.
basenm = os.path.normcase(os.path.basename(fnm))
digest = cacheDigest(fnm)
cachedfile = os.path.join(cachedir, basenm)
cmd = None
if cache_index.has_key(basenm):
if digest != cache_index[basenm]:
os.remove(cachedfile)
else:
return cachedfile
if upx:
if strip:
fnm = checkCache(fnm, 1, 0)
bestopt = "--best"
# FIXME: Linux builds of UPX do not seem to contain LZMA (they assert out)
# A better configure-time check is due.
if config["hasUPX"] >= (3,) and os.name == "nt":
bestopt = "--lzma"
upx_executable = "upx"
if config.get('upx_dir'):
upx_executable = os.path.join(config['upx_dir'], upx_executable)
cmd = '"' + upx_executable + '" ' + bestopt + " -q \"%s\"" % cachedfile
else:
if strip:
# -S = strip only debug symbols.
# The default strip behaviour breaks some shared libraries
# under Mac OSX.
cmd = "strip -S \"%s\"" % cachedfile
shutil.copy2(fnm, cachedfile)
os.chmod(cachedfile, 0755)
if pyasm and fnm.lower().endswith(".pyd"):
# If python.exe has dependent assemblies, check for embedded manifest
# of cached pyd file because we may need to 'fix it' for pyinstaller
try:
res = winmanifest.GetManifestResources(os.path.abspath(cachedfile))
except winresource.pywintypes.error, e:
if e.args[0] == winresource.ERROR_BAD_EXE_FORMAT:
# Not a win32 PE file
pass
else:
print "E:", os.path.abspath(cachedfile)
raise
else:
if winmanifest.RT_MANIFEST in res and len(res[winmanifest.RT_MANIFEST]):
for name in res[winmanifest.RT_MANIFEST]:
for language in res[winmanifest.RT_MANIFEST][name]:
try:
manifest = winmanifest.Manifest()
manifest.filename = ":".join([cachedfile,
str(winmanifest.RT_MANIFEST),
str(name),
str(language)])
manifest.parse_string(res[winmanifest.RT_MANIFEST][name][language],
False)
except Exception, exc:
print ("E: Cannot parse manifest resource %s, "
"%s from") % (name, language)
print "E:", cachedfile
print "E:", traceback.format_exc()
else:
# Fix the embedded manifest (if any):
# Extension modules built with Python 2.6.5 have
# an empty <dependency> element, we need to add
# dependentAssemblies from python.exe for
# pyinstaller
olen = len(manifest.dependentAssemblies)
for pydep in pyasm:
if not pydep.name in [dep.name for dep in
manifest.dependentAssemblies]:
print ("Adding %s to dependent assemblies "
"of %s") % (pydep.name, cachedfile)
manifest.dependentAssemblies.append(pydep)
if len(manifest.dependentAssemblies) > olen:
try:
manifest.update_resources(os.path.abspath(cachedfile),
[name],
[language])
except Exception, e:
print "E:", os.path.abspath(cachedfile)
raise
if cmd: system(cmd)
# update cache index
cache_index[basenm] = digest
_save_data(cacheindexfn, cache_index)
return cachedfile
UNCOMPRESSED, COMPRESSED, ENCRYPTED = range(3)
class PKG(Target):
typ = 'PKG'
xformdict = {'PYMODULE' : 'm',
'PYSOURCE' : 's',
'EXTENSION' : 'b',
'PYZ' : 'z',
'PKG' : 'a',
'DATA': 'x',
'BINARY': 'b',
'ZIPFILE': 'Z',
'EXECUTABLE': 'b'}
def __init__(self, toc, name=None, cdict=None, exclude_binaries=0,
strip_binaries=0, upx_binaries=0, crypt=0):
Target.__init__(self)
self.toc = toc
self.cdict = cdict
self.name = name
self.exclude_binaries = exclude_binaries
self.strip_binaries = strip_binaries
self.upx_binaries = upx_binaries
self.crypt = crypt
if name is None:
self.name = self.out[:-3] + 'pkg'
if self.cdict is None:
if config['useZLIB']:
self.cdict = {'EXTENSION':COMPRESSED,
'DATA':COMPRESSED,
'BINARY':COMPRESSED,
'EXECUTABLE':COMPRESSED,
'PYSOURCE':COMPRESSED,
'PYMODULE':COMPRESSED }
if self.crypt:
self.cdict['PYSOURCE'] = ENCRYPTED
self.cdict['PYMODULE'] = ENCRYPTED
else:
self.cdict = { 'PYSOURCE':UNCOMPRESSED }
self.__postinit__()
GUTS = (('name', _check_guts_eq),
('cdict', _check_guts_eq),
('toc', _check_guts_toc_mtime),
('exclude_binaries', _check_guts_eq),
('strip_binaries', _check_guts_eq),
('upx_binaries', _check_guts_eq),
('crypt', _check_guts_eq),
)
def check_guts(self, last_build):
_rmdir(self.name)
if not os.path.exists(self.name):
print "rebuilding %s because %s is missing" % (self.outnm, os.path.basename(self.name))
return 1
data = Target.get_guts(self, last_build)
if not data:
return True
# todo: toc equal
return False
def assemble(self):
print "building PKG", os.path.basename(self.name)
trash = []
mytoc = []
seen = {}
toc = addSuffixToExtensions(self.toc)
for inm, fnm, typ in toc:
if not os.path.isfile(fnm) and check_egg(fnm):
# file is contained within python egg, it is added with the egg
continue
if typ in ('BINARY', 'EXTENSION'):
if self.exclude_binaries:
self.dependencies.append((inm, fnm, typ))
else:
fnm = checkCache(fnm, self.strip_binaries,
self.upx_binaries and ( iswin or cygwin )
and config['hasUPX'])
# Avoid importing the same binary extension twice. This might
# happen if they come from different sources (eg. once from
# binary dependence, and once from direct import).
if typ == 'BINARY' and seen.has_key(fnm):
continue
seen[fnm] = 1
mytoc.append((inm, fnm, self.cdict.get(typ,0),
self.xformdict.get(typ,'b')))
elif typ == 'OPTION':
mytoc.append((inm, '', 0, 'o'))
else:
mytoc.append((inm, fnm, self.cdict.get(typ,0), self.xformdict.get(typ,'b')))
archive = carchive.CArchive()
archive.build(self.name, mytoc)
_save_data(self.out,
(self.name, self.cdict, self.toc, self.exclude_binaries,
self.strip_binaries, self.upx_binaries, self.crypt))
for item in trash:
os.remove(item)
return 1
class EXE(Target):
typ = 'EXECUTABLE'
exclude_binaries = 0
append_pkg = 1
def __init__(self, *args, **kws):
Target.__init__(self)
self.console = kws.get('console',1)
self.debug = kws.get('debug',0)
self.name = kws.get('name',None)
self.icon = kws.get('icon',None)
self.versrsrc = kws.get('version',None)
self.manifest = kws.get('manifest',None)
self.resources = kws.get('resources',[])
self.strip = kws.get('strip',None)
self.upx = kws.get('upx',None)
self.crypt = kws.get('crypt', 0)
self.exclude_binaries = kws.get('exclude_binaries',0)
self.append_pkg = kws.get('append_pkg', self.append_pkg)
if self.name is None:
self.name = self.out[:-3] + 'exe'
if not os.path.isabs(self.name):
self.name = os.path.join(SPECPATH, self.name)
if target_iswin or cygwin:
self.pkgname = self.name[:-3] + 'pkg'
else:
self.pkgname = self.name + '.pkg'
self.toc = TOC()
for arg in args:
if isinstance(arg, TOC):
self.toc.extend(arg)
elif isinstance(arg, Target):
self.toc.append((os.path.basename(arg.name), arg.name, arg.typ))
self.toc.extend(arg.dependencies)
else:
self.toc.extend(arg)
if iswin:
if sys.version[:3] == '1.5':
import exceptions
toc.append((os.path.basename(exceptions.__file__), exceptions.__file__, 'BINARY'))
if self.manifest:
if isinstance(self.manifest, basestring) and "<" in self.manifest:
# Assume XML string
self.manifest = winmanifest.ManifestFromXML(self.manifest)
elif not isinstance(self.manifest, winmanifest.Manifest):
# Assume filename
self.manifest = winmanifest.ManifestFromXMLFile(self.manifest)
else:
self.manifest = winmanifest.ManifestFromXMLFile(os.path.join(BUILDPATH,
specnm + ".exe.manifest"))
self.manifest.name = os.path.splitext(os.path.basename(self.name))[0]
if self.manifest.filename != os.path.join(BUILDPATH,
specnm + ".exe.manifest"):
# Update dependent assemblies
depmanifest = winmanifest.ManifestFromXMLFile(os.path.join(BUILDPATH,
specnm + ".exe.manifest"))
for assembly in depmanifest.dependentAssemblies:
if not assembly.name in [dependentAssembly.name
for dependentAssembly in
self.manifest.dependentAssemblies]:
self.manifest.dependentAssemblies.append(assembly)
if not self.console and \
not "Microsoft.Windows.Common-Controls" in [dependentAssembly.name
for dependentAssembly in
self.manifest.dependentAssemblies]:
# Add Microsoft.Windows.Common-Controls to dependent assemblies
self.manifest.dependentAssemblies.append(winmanifest.Manifest(type_="win32",
name="Microsoft.Windows.Common-Controls",
language="*",
processorArchitecture="x86",
version=(6, 0, 0, 0),
publicKeyToken="6595b64144ccf1df"))
self.manifest.writeprettyxml(os.path.join(BUILDPATH,
specnm + ".exe.manifest"))
self.toc.append((os.path.basename(self.name) + ".manifest",
os.path.join(BUILDPATH,
specnm + ".exe.manifest"),
'BINARY'))
self.pkg = PKG(self.toc, cdict=kws.get('cdict',None), exclude_binaries=self.exclude_binaries,
strip_binaries=self.strip, upx_binaries=self.upx, crypt=self.crypt)
self.dependencies = self.pkg.dependencies
self.__postinit__()
GUTS = (('name', _check_guts_eq),
('console', _check_guts_eq),
('debug', _check_guts_eq),
('icon', _check_guts_eq),
('versrsrc', _check_guts_eq),
('manifest', _check_guts_eq),
('resources', _check_guts_eq),
('strip', _check_guts_eq),
('upx', _check_guts_eq),
('crypt', _check_guts_eq),
('mtm', None,), # checked bellow
)
def check_guts(self, last_build):
_rmdir(self.name)
if not os.path.exists(self.name):
print "rebuilding %s because %s missing" % (self.outnm, os.path.basename(self.name))
return 1
if not self.append_pkg and not os.path.exists(self.pkgname):
print "rebuilding because %s missing" % (
os.path.basename(self.pkgname),)
return 1
data = Target.get_guts(self, last_build)
if not data:
return True
icon, versrsrc, manifest, resources = data[3:7]
if (icon or versrsrc or manifest or resources) and not config['hasRsrcUpdate']:
# todo: really ignore :-)
print "ignoring icon, version, manifest and resources = platform not capable"
mtm = data[-1]
crypt = data[-2]
if crypt != self.crypt:
print "rebuilding %s because crypt option changed" % outnm
return 1
if mtm != mtime(self.name):
print "rebuilding", self.outnm, "because mtimes don't match"
return True
if mtm < mtime(self.pkg.out):
print "rebuilding", self.outnm, "because pkg is more recent"
return True
return False
def _bootloader_file(self, exe):
try:
import platform
# On some Windows installation (Python 2.4) platform.system() is
# broken and incorrectly returns 'Microsoft' instead of 'Windows'.
# http://mail.python.org/pipermail/patches/2007-June/022947.html
syst = platform.system()
syst_real = {'Microsoft': 'Windows'}.get(syst, syst)
PLATFORM = syst_real + "-" + architecture()
except ImportError:
import os
n = { "nt": "Windows", "linux2": "Linux", "darwin": "Darwin" }
PLATFORM = n[os.name] + "-32bit"
if not self.console:
exe = exe + 'w'
if self.debug:
exe = exe + '_d'
import os
return os.path.join('support', 'loader', PLATFORM, exe)
def assemble(self):
print "building EXE from", os.path.basename(self.out)
trash = []
if not os.path.exists(os.path.dirname(self.name)):
os.makedirs(os.path.dirname(self.name))
outf = open(self.name, 'wb')
exe = self._bootloader_file('run')
exe = os.path.join(HOMEPATH, exe)
if target_iswin or cygwin:
exe = exe + '.exe'
if config['hasRsrcUpdate'] and (self.icon or self.versrsrc or
self.resources):
tmpnm = tempfile.mktemp()
shutil.copy2(exe, tmpnm)
os.chmod(tmpnm, 0755)
if self.icon:
icon.CopyIcons(tmpnm, self.icon)
if self.versrsrc:
versionInfo.SetVersion(tmpnm, self.versrsrc)
for res in self.resources:
res = res.split(",")
for i in range(len(res[1:])):
try:
res[i + 1] = int(res[i + 1])