-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstall_deps.py
1882 lines (1556 loc) · 80.5 KB
/
install_deps.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
from __future__ import print_function
from distutils.spawn import find_executable
from distutils.dir_util import copy_tree
import argparse
import textwrap
import codecs
import contextlib
import ctypes
import datetime
import distutils
import fnmatch
import ntpath
import glob
import locale
import multiprocessing
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
import sysconfig
import tarfile
import zipfile
import rarfile
if sys.version_info.major >= 3:
from urllib.request import urlopen
else:
from urllib2 import urlopen
# Helpers for printing output
verbosity = 1
def Print(msg):
if verbosity > 0:
print(msg)
def PrintWarning(warning):
if verbosity > 0:
print("WARNING:", warning)
def PrintStatus(status):
if verbosity >= 1:
print("STATUS:", status)
def PrintInfo(info):
if verbosity >= 2:
print("INFO:", info)
def PrintCommandOutput(output):
if verbosity >= 3:
sys.stdout.write(output)
def PrintError(error):
if verbosity >= 3 and sys.exc_info()[1] is not None:
import traceback
traceback.print_exc()
print ("ERROR:", error)
# Helpers for determining platform
def Windows():
return platform.system() == "Windows"
def Linux():
return platform.system() == "Linux"
def MacOS():
return platform.system() == "Darwin"
INSTALL_DIR = ""
if Windows():
INSTALL_DIR = "../../../lib/win64_vc15"
elif Linux():
INSTALL_DIR = "../../../lib/linux_centos7_x86_64"
SOURCE_DIR = "../../../lib/win64_vc15/build_env/source"
BUILD_DIR = "../../../lib/win64_vc15/build_env/build"
def Python3():
return sys.version_info.major == 3
def GetLocale():
return sys.stdout.encoding or locale.getdefaultlocale()[1] or "UTF-8"
def GetCommandOutput(command):
"""Executes the specified command and returns output or None."""
try:
return subprocess.check_output(
shlex.split(command),
stderr=subprocess.STDOUT).decode(GetLocale(), 'replace').strip()
except subprocess.CalledProcessError:
pass
return None
def GetXcodeDeveloperDirectory():
"""Returns the active developer directory as reported by 'xcode-select -p'.
Returns None if none is set."""
if not MacOS():
return None
return GetCommandOutput("xcode-select -p")
def GetVisualStudioCompilerAndVersion():
"""Returns a tuple containing the path to the Visual Studio compiler
and a tuple for its version, e.g. (14, 0). If the compiler is not found
or version number cannot be determined, returns None."""
if not Windows():
return None
msvcCompiler = find_executable('cl')
if msvcCompiler:
# VisualStudioVersion environment variable should be set by the
# Visual Studio Command Prompt.
match = re.search(
r"(\d+)\.(\d+)",
os.environ.get("VisualStudioVersion", ""))
if match:
return (msvcCompiler, tuple(int(v) for v in match.groups()))
return None
def IsVisualStudioVersionOrGreater(desiredVersion):
if not Windows():
return False
msvcCompilerAndVersion = GetVisualStudioCompilerAndVersion()
if msvcCompilerAndVersion:
_, version = msvcCompilerAndVersion
return version >= desiredVersion
return False
def IsVisualStudio2019OrGreater():
VISUAL_STUDIO_2019_VERSION = (16, 0)
return IsVisualStudioVersionOrGreater(VISUAL_STUDIO_2019_VERSION)
def IsVisualStudio2017OrGreater():
VISUAL_STUDIO_2017_VERSION = (15, 0)
return IsVisualStudioVersionOrGreater(VISUAL_STUDIO_2017_VERSION)
def IsVisualStudio2015OrGreater():
VISUAL_STUDIO_2015_VERSION = (14, 0)
return IsVisualStudioVersionOrGreater(VISUAL_STUDIO_2015_VERSION)
def GetPythonInfo():
python_version = "3.9"
python_version_no_dot = "39"
def _GetPythonLibraryFilename():
if Windows():
return "python" + python_version_no_dot + ".lib"
elif Linux():
return "libpython" + python_version + ".a"
elif MacOS():
return "libpython" + python_version + ".dylib"
else:
raise RuntimeError("Platform not supported")
def _GetPythonEXEFilename():
if Windows():
return "python" + ".exe"
elif Linux():
return "python" + python_version + ".so"
elif MacOS():
return "python" + python_version + ".so"
else:
raise RuntimeError("Platform not supported")
python_dir = ""
python_include = ""
python_lib = ""
python_exe = ""
if Windows():
python_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), f"../../../lib/win64_vc15/python/{python_version_no_dot}")
python_include = os.path.join(python_dir, "include")
python_lib = os.path.join(python_dir, "libs")
python_exe = os.path.join(python_dir, "bin", _GetPythonEXEFilename())
elif Linux():
python_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../../lib/linux_centos7_x86_64/python")
python_include = os.path.join(python_dir, "include")
python_lib = os.path.join(python_dir, "lib", _GetPythonLibraryFilename())
python_exe = os.path.join(python_dir, "bin", _GetPythonEXEFilename())
elif MacOS():
python_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../../lib/FIX_ME/python")
python_include = os.path.join(python_dir, "include")
python_lib = os.path.join(python_dir, "lib", _GetPythonLibraryFilename())
python_exe = os.path.join(python_dir, "bin", _GetPythonEXEFilename())
else:
raise RuntimeError("Platform not supported")
python_info = {"python_include": python_include.replace('\\', '/'),
"python_lib": python_lib.replace('\\', '/'),
"python_exe": python_exe.replace('\\', '/'),
"python_version": python_version}
return python_info
def GetCPUCount():
try:
return multiprocessing.cpu_count()
except NotImplementedError:
return 1
def Run(cmd, logCommandOutput = True):
"""Run the specified command in a subprocess."""
PrintInfo('Running "{cmd}"'.format(cmd=cmd))
with codecs.open("log.txt", "a", "utf-8") as logfile:
logfile.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
logfile.write("\n")
logfile.write(cmd)
logfile.write("\n")
# Let exceptions escape from subprocess calls -- higher level
# code will handle them.
if logCommandOutput:
p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
l = p.stdout.readline().decode(GetLocale(), 'replace')
if l:
logfile.write(l)
PrintCommandOutput(l)
elif p.poll() is not None:
break
else:
p = subprocess.Popen(shlex.split(cmd))
p.wait()
if p.returncode != 0:
# If verbosity >= 3, we'll have already been printing out command output
# so no reason to print the log file again.
if verbosity < 3:
with open("log.txt", "r") as logfile:
Print(logfile.read())
raise RuntimeError("Failed to run '{cmd}'\nSee {log} for more details."
.format(cmd=cmd, log=os.path.abspath("log.txt")))
@contextlib.contextmanager
def CurrentWorkingDirectory(dir):
"""Context manager that sets the current working directory to the given
directory and resets it to the original directory when closed."""
curdir = os.getcwd()
os.chdir(dir)
try: yield
finally: os.chdir(curdir)
def CopyFiles(context, src, dest):
"""Copy files like shutil.copy, but src may be a glob pattern."""
filesToCopy = glob.glob(src)
if not filesToCopy:
raise RuntimeError("File(s) to copy {src} not found".format(src=src))
instDestDir = os.path.join(context.libInstDir, dest)
for f in filesToCopy:
PrintCommandOutput("Copying {file} to {destDir}\n"
.format(file=f, destDir=instDestDir))
shutil.copy(f, instDestDir)
def CopyDirectory(context, srcDir, destDir):
"""Copy directory like shutil.copytree."""
instDestDir = os.path.join(context.libInstDir, destDir)
if os.path.isdir(instDestDir):
shutil.rmtree(instDestDir)
PrintCommandOutput("Copying {srcDir} to {destDir}\n"
.format(srcDir=srcDir, destDir=instDestDir))
shutil.copytree(srcDir, instDestDir)
def FormatMultiProcs(numJobs, generator):
tag = "-j"
if generator:
if "Visual Studio" in generator:
tag = "/M:"
elif "Xcode" in generator:
tag = "-j "
return "{tag}{procs}".format(tag=tag, procs=numJobs)
def RunCMake(context, force, extraArgs = None):
"""Invoke CMake to configure, build, and install a library whose
source code is located in the current working directory."""
# Create a directory for out-of-source builds in the build directory
# using the name of the current working directory.
srcDir = os.getcwd()
libInstDir = (context.libInstDir)
buildDir = os.path.join(context.buildDir, os.path.split(srcDir)[1])
# if force and os.path.isdir(buildDir):
# shutil.rmtree(buildDir)
if not os.path.isdir(buildDir):
os.makedirs(buildDir)
generator = context.cmakeGenerator
# On Windows, we need to explicitly specify the generator to ensure we're
# building a 64-bit project. (Surely there is a better way to do this?)
# TODO: figure out exactly what "vcvarsall.bat x64" sets to force x64
if generator is None and Windows():
if IsVisualStudio2019OrGreater():
generator = "Visual Studio 16 2019"
elif IsVisualStudio2017OrGreater():
generator = "Visual Studio 15 2017 Win64"
else:
generator = "Visual Studio 14 2015 Win64"
if generator is not None:
generator = '-G "{gen}"'.format(gen=generator)
if IsVisualStudio2019OrGreater():
generator = generator + " -A x64"
toolset = context.cmakeToolset
if toolset is not None:
toolset = '-T "{toolset}"'.format(toolset=toolset)
# On MacOS, enable the use of @rpath for relocatable builds.
osx_rpath = None
if MacOS():
osx_rpath = "-DCMAKE_MACOSX_RPATH=ON"
# We use -DCMAKE_BUILD_TYPE for single-configuration generators
# (Ninja, make), and --config for multi-configuration generators
# (Visual Studio); technically we don't need BOTH at the same
# time, but specifying both is simpler than branching
config=("Debug" if context.buildDebug else "Release")
with CurrentWorkingDirectory(buildDir):
Run('cmake '
'-DCMAKE_INSTALL_PREFIX="{libInstDir}" '
'-DCMAKE_PREFIX_PATH="{libInstDir}" '
'-DCMAKE_BUILD_TYPE={config} '
'{osx_rpath} '
'{generator} '
'{toolset} '
'{extraArgs} '
'"{srcDir}"'
.format(libInstDir=libInstDir,
depsInstDir=context.libInstDir,
config=config,
srcDir=srcDir,
osx_rpath=(osx_rpath or ""),
generator=(generator or ""),
toolset=(toolset or ""),
extraArgs=(" ".join(extraArgs) if extraArgs else "")))
Run("cmake --build . --config {config} --target install -- {multiproc}"
.format(config=config,
multiproc=FormatMultiProcs(context.numJobs, generator)))
def GetCMakeVersion():
"""
Returns the CMake version as tuple of integers (major, minor) or
(major, minor, patch) or None if an error occured while launching cmake and
parsing its output.
"""
output_string = GetCommandOutput("cmake --version")
if not output_string:
PrintWarning("Could not determine cmake version -- please install it "
"and adjust your PATH")
return None
# cmake reports, e.g., "... version 3.14.3"
match = re.search(r"version (\d+)\.(\d+)(\.(\d+))?", output_string)
if not match:
PrintWarning("Could not determine cmake version")
return None
major, minor, patch_group, patch = match.groups()
if patch_group is None:
return (int(major), int(minor))
else:
return (int(major), int(minor), int(patch))
def PatchFile(filename, patches, multiLineMatches=False):
"""Applies patches to the specified file. patches is a list of tuples
(old string, new string)."""
if multiLineMatches:
oldLines = [open(filename, 'r').read()]
else:
oldLines = open(filename, 'r').readlines()
newLines = oldLines
for (oldString, newString) in patches:
newLines = [s.replace(oldString, newString) for s in newLines]
if newLines != oldLines:
PrintInfo("Patching file {filename} (original in {oldFilename})..."
.format(filename=filename, oldFilename=filename + ".old"))
shutil.copy(filename, filename + ".old")
open(filename, 'w').writelines(newLines)
def InstallDependency(src, dest):
src = context.libInstDir + src
dest = context.libInstDir + dest
try:
os.remove(dest)
except:
if os.path.exists(dest):
shutil.rmtree(dest)
os.makedirs(os.path.dirname(dest), exist_ok=True)
try:
copy_tree(src, dest)
except:
shutil.copyfile(src, dest)
def DownloadFileWithCurl(url, outputFilename):
# Don't log command output so that curl's progress
# meter doesn't get written to the log file.
Run("curl {progress} -L -o {filename} {url}".format(
progress="-#" if verbosity >= 2 else "-s",
filename=outputFilename, url=url),
logCommandOutput=False)
def DownloadFileWithPowershell(url, outputFilename):
# It's important that we specify to use TLS v1.2 at least or some
# of the downloads will fail.
cmd = "powershell [Net.ServicePointManager]::SecurityProtocol = \
[Net.SecurityProtocolType]::Tls12; \"(new-object \
System.Net.WebClient).DownloadFile('{url}', '{filename}')\""\
.format(filename=outputFilename, url=url)
Run(cmd,logCommandOutput=False)
def DownloadFileWithUrllib(url, outputFilename):
r = urlopen(url)
with open(outputFilename, "wb") as outfile:
outfile.write(r.read())
def DownloadURL(url, context, force, dontExtract = None):
"""Download and extract the archive file at given URL to the
source directory specified in the context.
dontExtract may be a sequence of path prefixes that will
be excluded when extracting the archive.
Returns the absolute path to the directory where files have
been extracted."""
with CurrentWorkingDirectory(context.srcDir):
# Extract filename from URL and see if file already exists.
filename = url.split("/")[-1]
if os.path.exists(filename):
os.remove(filename)
if os.path.exists(filename):
PrintInfo("{0} already exists, skipping download".format(os.path.abspath(filename)))
else:
PrintInfo("Downloading {0} to {1}"
.format(url, os.path.abspath(filename)))
# To work around occasional hiccups with downloading from websites
# (SSL validation errors, etc.), retry a few times if we don't
# succeed in downloading the file.
maxRetries = 5
lastError = None
# Download to a temporary file and rename it to the expected
# filename when complete. This ensures that incomplete downloads
# will be retried if the script is run again.
tmpFilename = filename + ".tmp"
if os.path.exists(tmpFilename):
os.remove(tmpFilename)
for i in range(maxRetries):
try:
context.downloader(url, tmpFilename)
break
except Exception as e:
PrintCommandOutput("Retrying download due to error: {err}\n"
.format(err=e))
lastError = e
else:
errorMsg = str(lastError)
if "SSL: TLSV1_ALERT_PROTOCOL_VERSION" in errorMsg:
errorMsg += ("\n\n"
"Your OS or version of Python may not support "
"TLS v1.2+, which is required for downloading "
"files from certain websites. This support "
"was added in Python 2.7.9."
"\n\n"
"You can use curl to download dependencies "
"by installing it in your PATH and re-running "
"this script.")
raise RuntimeError("Failed to download {url}: {err}"
.format(url=url, err=errorMsg))
shutil.move(tmpFilename, filename)
# Open the archive and retrieve the name of the top-most directory.
# This assumes the archive contains a single directory with all
# of the contents beneath it.
archive = None
rootDir = None
members = None
try:
if tarfile.is_tarfile(filename):
archive = tarfile.open(filename)
rootDir = archive.getnames()[0].split('/')[0]
if dontExtract != None:
members = (m for m in archive.getmembers()
if not any((fnmatch.fnmatch(m.name, p)
for p in dontExtract)))
elif zipfile.is_zipfile(filename):
archive = zipfile.ZipFile(filename)
rootDir = archive.namelist()[0].split('/')[0]
if dontExtract != None:
members = (m for m in archive.getnames()
if not any((fnmatch.fnmatch(m, p)
for p in dontExtract)))
elif rarfile.is_rarfile(filename):
archive = rarfile.RarFile(filename)
rootDir = archive.namelist()[0].split('/')[0]
if dontExtract != None:
members = (m for m in archive.getnames()
if not any((fnmatch.fnmatch(m, p)
for p in dontExtract)))
else:
raise RuntimeError("unrecognized archive file type")
with archive:
extractedPath = os.path.abspath(rootDir)
# if force and os.path.isdir(extractedPath):
# shutil.rmtree(extractedPath)
if os.path.isdir(extractedPath):
PrintInfo("Directory {0} already exists, skipping extract".format(extractedPath))
else:
PrintInfo("Extracting archive to {0}".format(extractedPath))
# Extract to a temporary directory then move the contents
# to the expected location when complete. This ensures that
# incomplete extracts will be retried if the script is run
# again.
tmpExtractedPath = os.path.abspath("extract_dir")
if os.path.isdir(tmpExtractedPath):
shutil.rmtree(tmpExtractedPath)
archive.extractall(tmpExtractedPath, members=members)
shutil.move(os.path.join(tmpExtractedPath, rootDir),
extractedPath)
shutil.rmtree(tmpExtractedPath)
return extractedPath
except Exception as e:
# If extraction failed for whatever reason, assume the
# archive file was bad and move it aside so that re-running
# the script will try downloading and extracting again.
shutil.move(filename, filename + ".bad")
raise RuntimeError("Failed to extract archive {filename}: {err}".format(filename=filename, err=e))
############################################################
# 3rd-Party Dependencies
AllDependencies = list()
AllDependenciesByName = dict()
class Dependency(object):
def __init__(self, name, installer, *files):
self.name = name
self.installer = installer
self.filesToCheck = files
AllDependencies.append(self)
AllDependenciesByName.setdefault(name.lower(), self)
def Exists(self, context):
return all([os.path.isfile(os.path.join(context.libInstDir, f))
for f in self.filesToCheck])
class PythonDependency(object):
def __init__(self, name, getInstructions, moduleNames):
self.name = name
self.getInstructions = getInstructions
self.moduleNames = moduleNames
def Exists(self, context):
# If one of the modules in our list imports successfully, we are good.
for moduleName in self.moduleNames:
try:
pyModule = __import__(moduleName)
return True
except:
pass
return False
def AnyPythonDependencies(deps):
return any([type(d) is PythonDependency for d in deps])
############################################################
# zlib
ZLIB_URL = "https://github.com/madler/zlib/archive/refs/tags/v1.2.11.zip"
def InstallZlib(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(ZLIB_URL, context, force)):
RunCMake(context, force, buildArgs)
InstallDependency("/bin/zlib.dll", "/zlib/bin/zlib.dll")
InstallDependency("/lib/zlib.lib", "/zlib/lib/zlib.lib")
InstallDependency("/lib/zlibstatic.lib", "/zlib/lib/zlibstatic.lib")
InstallDependency("/include/zlib.h", "/zlib/include/zlib.h")
InstallDependency("/include/zconf.h", "/zlib/include/zconf.h")
ZLIB = Dependency("zlib", InstallZlib, "include/zlib.h")
############################################################
# boost
if MacOS():
BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.tar.gz"
BOOST_VERSION_FILE = "include/boost/version.hpp"
elif Linux():
if Python3():
BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.tar.gz"
else:
BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.tar.gz"
BOOST_VERSION_FILE = "include/boost/version.hpp"
elif Windows():
# The default installation of boost on Windows puts headers in a versioned
# subdirectory, which we have to account for here. In theory, specifying
# "layout=system" would make the Windows install match Linux/MacOS, but that
# causes problems for other dependencies that look for boost.
#
# boost 1.70 is required for Visual Studio 2019. For simplicity, we use
# this version for all older Visual Studio versions as well.
BOOST_URL = "https://boostorg.jfrog.io/artifactory/main/release/1.76.0/source/boost_1_76_0.zip"
BOOST_VERSION_FILE = "include/boost-1_76/boost/version.hpp"
def InstallBoost_Helper(context, force, buildArgs):
force = True
# Documentation files in the boost archive can have exceptionally
# long paths. This can lead to errors when extracting boost on Windows,
# since paths are limited to 260 characters by default on that platform.
# To avoid this, we skip extracting all documentation.
#
# For some examples, see: https://svn.boost.org/trac10/ticket/11677
dontExtract = ["*/doc/*", "*/libs/*/doc/*"]
with CurrentWorkingDirectory(DownloadURL(BOOST_URL, context, force, dontExtract)):
bootstrap = "bootstrap.bat" if Windows() else "./bootstrap.sh"
Run('{bootstrap} --prefix="{libInstDir}"'.format(bootstrap=bootstrap, libInstDir=context.libInstDir + "/boost"))
# b2 supports at most -j64 and will error if given a higher value.
num_procs = min(64, context.numJobs)
boost_user_config_jam = "{buildDir}/boost.user-config.jam".format(buildDir=context.buildDir)
boost_build_options = [
'--prefix="{libInstDir}"'.format(libInstDir=context.libInstDir + "/boost"),
'--build-dir="{buildDir}"'.format(buildDir=context.buildDir),
'-j{procs}'.format(procs=num_procs),
'address-model=64',
'link=shared',
'runtime-link=shared',
'threading=multi',
'variant={variant}'.format(variant="debug" if context.buildDebug else "release"),
'--with-atomic',
'--with-program_options',
'--with-regex',
'--with-python',
'--with-date_time',
'--with-system',
'--with-thread',
'--with-iostreams',
"--with-filesystem",
'-sNO_BZIP2=1',
'--user-config={boost_user_config_jam}'.format(boost_user_config_jam=boost_user_config_jam).replace('\\', '/'),
]
pythonInfo = GetPythonInfo()
PYTHON_SHORT_VERSION = pythonInfo["python_version"]
PYTHON_BINARY = pythonInfo["python_exe"]
PYTHON_INCLUDE = pythonInfo["python_include"]
PYTHON_LIB = pythonInfo["python_lib"]
with open(boost_user_config_jam, 'w') as patch_boost:
patch_boost.write(f'using python : {PYTHON_SHORT_VERSION} : {PYTHON_BINARY}\n')
patch_boost.write(f' : {PYTHON_INCLUDE}\n')
patch_boost.write(f' : {PYTHON_LIB}\n')
patch_boost.write(f';')
patch_boost.close()
if force:
boost_build_options.append("-a")
if Windows():
# toolset parameter for Visual Studio documented here:
# https://github.com/boostorg/build/blob/develop/src/tools/msvc.jam
if context.cmakeToolset == "v142":
boost_build_options.append("toolset=msvc-14.2")
elif context.cmakeToolset == "v141":
boost_build_options.append("toolset=msvc-14.1")
elif context.cmakeToolset == "v140":
boost_build_options.append("toolset=msvc-14.0")
elif IsVisualStudio2019OrGreater():
boost_build_options.append("toolset=msvc-14.2")
elif IsVisualStudio2017OrGreater():
boost_build_options.append("toolset=msvc-14.1")
else:
boost_build_options.append("toolset=msvc-14.2")
if MacOS():
# Must specify toolset=clang to ensure install_name for boost
# libraries includes @rpath
boost_build_options.append("toolset=clang")
# Add on any user-specified extra arguments.
# boost_build_options += buildArgs
build_command = "b2" if Windows() else "./b2"
Run('{build_command} {options} install'.format(build_command=build_command, options=" ".join(boost_build_options)))
def InstallBoost(context, force, buildArgs):
# Boost's build system will install the version.hpp header before
# building its libraries. We make sure to remove it in case of
# any failure to ensure that the build script detects boost as a
# dependency to build the next time it's run.
try:
InstallBoost_Helper(context, force, buildArgs)
except:
versionHeader = os.path.join(context.libInstDir + "/boost", BOOST_VERSION_FILE)
if os.path.isfile(versionHeader):
try: os.remove(versionHeader)
except: pass
raise
BOOST = Dependency("boost", InstallBoost, BOOST_VERSION_FILE)
############################################################
# Intel TBB
if Windows():
TBB_URL = "https://github.com/oneapi-src/oneTBB/releases/download/v2021.1.1/oneapi-tbb-2021.1.1-win.zip"
else:
TBB_URL = "https://github.com/oneapi-src/oneTBB/releases/download/v2021.1.1/oneapi-tbb-2021.1.1-lin.tgz"
def InstallTBB(context, force, buildArgs):
if Windows():
InstallTBB_Windows(context, force, buildArgs)
elif Linux() or MacOS():
InstallTBB_LinuxOrMacOS(context, force, buildArgs)
def InstallTBB_Windows(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(TBB_URL, context, force)):
# On Windows, we simply copy headers and pre-built DLLs to
# the appropriate location.
# if buildArgs:
# PrintWarning("Ignoring build arguments {}, TBB is "
# "not built from source on this platform."
# .format(buildArgs))
CopyFiles(context, "lib\\intel64\\vc14\\*.*", "lib")
CopyDirectory(context, "include\\oneapi", "include\\oneapi")
CopyDirectory(context, "include\\tbb", "include\\tbb")
def InstallTBB_LinuxOrMacOS(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(TBB_URL, context, force)):
# Note: TBB installation fails on OSX when cuda is installed, a
# suggested fix:
# https://github.com/spack/spack/issues/6000#issuecomment-358817701
if MacOS():
PatchFile("build/macos.inc",
[("shell clang -v ", "shell clang --version ")])
# TBB does not support out-of-source builds in a custom location.
Run('make -j{procs} {buildArgs}'
.format(procs=context.numJobs,
buildArgs=" ".join(buildArgs)))
# Install both release and debug builds. USD requires the debug
# libraries when building in debug mode, and installing both
# makes it easier for users to install dependencies in some
# location that can be shared by both release and debug USD
# builds. Plus, the TBB build system builds both versions anyway.
CopyFiles(context, "build/*_release/libtbb*.*", "lib")
CopyFiles(context, "build/*_debug/libtbb*.*", "lib")
CopyDirectory(context, "include/serial", "include/serial")
CopyDirectory(context, "include/tbb", "include/tbb")
TBB = Dependency("TBB", InstallTBB, "include/tbb/tbb.h")
############################################################
# JPEG
if Windows():
JPEG_URL = "https://storage.googleapis.com/dependency_links/libjpeg-turbo-2.0.90.zip"
else:
JPEG_URL = "https://www.ijg.org/files/jpegsrc.v9b.tar.gz"
def InstallJPEG(context, force, buildArgs):
if Windows():
InstallJPEG_Turbo(context, force, buildArgs)
else:
InstallJPEG_Lib(context, force, buildArgs)
def InstallJPEG_Turbo(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(JPEG_URL, context, force)):
RunCMake(context, force, buildArgs)
InstallDependency("/bin/cjpeg.exe", "/jpeg/bin/cjpeg.exe")
InstallDependency("/bin/djpeg.exe", "/jpeg/bin/djpeg.exe")
InstallDependency("/bin/jpeg62.dll", "/jpeg/bin/jpeg62.dll")
InstallDependency("/bin/jpegtran.exe", "/jpeg/bin/jpegtran.exe")
InstallDependency("/bin/rdjpgcom.exe", "/jpeg/bin/rdjpgcom.exe")
InstallDependency("/bin/tjbench.exe", "/jpeg/bin/tjbench.exe")
InstallDependency("/bin/turbojpeg.dll", "/jpeg/bin/turbojpeg.dll")
InstallDependency("/bin/wrjpgcom.exe", "/jpeg/bin/wrjpgcom.exe")
InstallDependency("/lib/jpeg.lib", "/jpeg/lib/jpeg.lib")
InstallDependency("/lib/jpeg-static.lib", "/jpeg/lib/jpeg-static.lib")
InstallDependency("/lib/turbojpeg.lib", "/jpeg/lib/turbojpeg.lib")
InstallDependency("/lib/turbojpeg-static.lib", "/jpeg/lib/turbojpeg-static.lib")
InstallDependency("/include/jconfig.h", "/jpeg/include/jconfig.h")
InstallDependency("/include/jerror.h", "/jpeg/include/jerror.h")
InstallDependency("/include/jmorecfg.h", "/jpeg/include/jmorecfg.h")
InstallDependency("/include/jpeglib.h", "/jpeg/include/jpeglib.h")
InstallDependency("/include/turbojpeg.h", "/jpeg/include/turbojpeg.h")
def InstallJPEG_Lib(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(JPEG_URL, context, force)):
Run('./configure --prefix="{libInstDir}" '
'--disable-static --enable-shared '
'{buildArgs}'
.format(libInstDir=context.libInstDir,
buildArgs=" ".join(buildArgs)))
Run('make -j{procs} install'
.format(procs=context.numJobs))
JPEG = Dependency("JPEG", InstallJPEG, "include/jpeglib.h")
############################################################
# TIFF
TIFF_URL = "https://gitlab.com/libtiff/libtiff/-/archive/v4.2.0/libtiff-v4.2.0.zip"
def InstallTIFF(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(TIFF_URL, context, force)):
# libTIFF has a build issue on Windows where tools/tiffgt.c
# unconditionally includes unistd.h, which does not exist.
# To avoid this, we patch the CMakeLists.txt to skip building
# the tools entirely. We do this on Linux and MacOS as well
# to avoid requiring some GL and X dependencies.
#
# We also need to skip building tests, since they rely on
# the tools we've just elided.
PatchFile("CMakeLists.txt",
[("add_subdirectory(tools)", "# add_subdirectory(tools)"),
("add_subdirectory(test)", "# add_subdirectory(test)")])
# The libTIFF CMakeScript says the ld-version-script
# functionality is only for compilers using GNU ld on
# ELF systems or systems which provide an emulation; therefore
# skipping it completely on mac and windows.
if MacOS() or Windows():
extraArgs = ["-Dld-version-script=OFF"]
else:
extraArgs = []
extraArgs += buildArgs
RunCMake(context, force, extraArgs)
InstallDependency("/bin/tiff.dll", "/tiff/bin/tiff.dll")
InstallDependency("/bin/tiffxx.dll", "/tiff/bin/tiffxx.dll")
InstallDependency("/lib/tiff.lib", "/tiff/lib/tiff.lib")
InstallDependency("/include/tiff.h", "/tiff/include/tiff.h")
InstallDependency("/include/tiffconf.h", "/tiff/include/tiffconf.h")
InstallDependency("/include/tiffio.h", "/tiff/include/tiffio.h")
InstallDependency("/include/tiffio.hxx", "/tiff/include/tiffio.hxx")
InstallDependency("/include/tiffvers.h", "/tiff/include/tiffvers.h")
TIFF = Dependency("TIFF", InstallTIFF, "include/tiff.h")
############################################################
# PNG
PNG_URL = "https://github.com/glennrp/libpng/archive/refs/tags/v1.6.35.zip"
def InstallPNG(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(PNG_URL, context, force)):
RunCMake(context, force, buildArgs)
InstallDependency("/bin/libpng16.dll", "/png/bin/libpng16.dll")
InstallDependency("/bin/pngfix.exe", "/png/bin/pngfix.exe")
InstallDependency("/bin/png-fix-itxt.exe", "/png/bin/png-fix-itxt.exe")
InstallDependency("/lib/libpng16.lib", "/png/lib/libpng16.lib")
InstallDependency("/lib/libpng16_static.lib", "/png/lib/libpng16_static.lib")
InstallDependency("/lib/libpng", "/png/lib/libpng")
InstallDependency("/include/pnglibconf.h", "/png/include/pnglibconf.h")
InstallDependency("/include/pngconf.h", "/png/include/pngconf.h")
InstallDependency("/include/png.h", "/png/include/png.h")
InstallDependency("/include/libpng16", "/png/include/libpng16")
PNG = Dependency("PNG", InstallPNG, "include/png.h")
############################################################
# Imath/OpenEXR
OPENEXR_URL = "https://github.com/openexr/openexr/archive/v3.0.0-beta.zip"
IMATH_URL = "https://github.com/AcademySoftwareFoundation/Imath/archive/refs/tags/v3.0.0-beta.zip"
def InstallOpenEXR(context, force, buildArgs):
# OPENEXR
exrDir = DownloadURL(OPENEXR_URL, context, force)
openexrSrcDir = os.path.join(exrDir, "")
with CurrentWorkingDirectory(openexrSrcDir):
RunCMake(context, force,
['-DILMBASE_PACKAGE_PREFIX="{libInstDir}"'
.format(libInstDir=context.libInstDir)] + buildArgs)
# IMATH
mathDir = DownloadURL(IMATH_URL, context, force)
imathSrcDir = os.path.join(mathDir, "")
with CurrentWorkingDirectory(imathSrcDir):
RunCMake(context, force,
['-DILMBASE_PACKAGE_PREFIX="{libInstDir}"'
.format(libInstDir=context.libInstDir)] + buildArgs)
InstallDependency("/bin/exr2aces.exe", "/openexr/bin/exr2aces.exe")
InstallDependency("/bin/exrenvmap.exe", "/openexr/bin/exrenvmap.exe")
InstallDependency("/bin/exrheader.exe", "/openexr/bin/exrheader.exe")
InstallDependency("/bin/exrmakepreview.exe", "/openexr/bin/exrmakepreview.exe")
InstallDependency("/bin/exrmaketiled.exe", "/openexr/bin/exrmaketiled.exe")
InstallDependency("/bin/exrmultipart.exe", "/openexr/bin/exrmultipart.exe")
InstallDependency("/bin/exrstdattr.exe", "/openexr/bin/exrstdattr.exe")
InstallDependency("/bin/Iex-3_0.dll", "/openexr/bin/Iex-3_0.dll")
InstallDependency("/bin/IlmThread-3_0.dll", "/openexr/bin/IlmThread-3_0.dll")
InstallDependency("/bin/Imath-3_0.dll", "/openexr/bin/Imath-3_0.dll")
InstallDependency("/bin/OpenEXR-3_0.dll", "/openexr/bin/OpenEXR-3_0.dll")
InstallDependency("/bin/OpenEXRUtil-3_0.dll", "/openexr/bin/OpenEXRUtil-3_0.dll")
InstallDependency("/lib/Iex-3_0.lib", "/openexr/lib/Iex-3_0.lib")
InstallDependency("/lib/IlmThread-3_0.lib", "/openexr/lib/IlmThread-3_0.lib")
InstallDependency("/lib/Imath-3_0.lib", "/openexr/lib/Imath-3_0.lib")
InstallDependency("/lib/OpenEXR-3_0.lib", "/openexr/lib/OpenEXR-3_0.lib")
InstallDependency("/lib/OpenEXRUtil-3_0.lib", "/openexr/lib/OpenEXRUtil-3_0.lib")
InstallDependency("/include/Imath", "/openexr/include/Imath")
InstallDependency("/include/OpenEXR", "/openexr/include/OpenEXR")
OPENEXR = Dependency("OpenEXR", InstallOpenEXR, "include/OpenEXR/ImfVersion.h")
############################################################
# Ptex
PTEX_URL = "https://github.com/wdas/ptex/archive/v2.3.2.zip"
def InstallPtex(context, force, buildArgs):
if Windows():
InstallPtex_Windows(context, force, buildArgs)
else:
InstallPtex_LinuxOrMacOS(context, force, buildArgs)
def InstallPtex_Windows(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(PTEX_URL, context, force)):
# Ptex has a bug where the import library for the dynamic library and
# the static library both get the same name, Ptex.lib, and as a
# result one clobbers the other. We hack the appropriate CMake
# file to prevent that. Since we don't need the static library we'll
# rename that.
#
# In addition src\tests\CMakeLists.txt adds -DPTEX_STATIC to the
# compiler but links tests against the dynamic library, causing the
# links to fail. We patch the file to not add the -DPTEX_STATIC
PatchFile('src\\ptex\\CMakeLists.txt',
[("set_target_properties(Ptex_static PROPERTIES OUTPUT_NAME Ptex)",
"set_target_properties(Ptex_static PROPERTIES OUTPUT_NAME Ptexs)")])
PatchFile('src\\tests\\CMakeLists.txt',
[("add_definitions(-DPTEX_STATIC)",
"# add_definitions(-DPTEX_STATIC)")])
# Patch Ptex::String to export symbol for operator<<
# This is required for newer versions of OIIO, which make use of the
# this operator on Windows platform specifically.
PatchFile('src\\ptex\\Ptexture.h',
[("std::ostream& operator << (std::ostream& stream, const Ptex::String& str);",
"PTEXAPI std::ostream& operator << (std::ostream& stream, const Ptex::String& str);")])
RunCMake(context, force, buildArgs)
InstallDependency("/bin/ptxinfo.exe", "/ptex/bin/ptxinfo.exe")
InstallDependency("/lib/Ptex.dll", "/ptex/lib/Ptex.dll")
InstallDependency("/lib/Ptex.lib", "/ptex/lib/Ptex.lib")
InstallDependency("/lib/Ptexs.lib", "/ptex/lib/Ptexs.lib")
InstallDependency("/include/PtexVersion.h", "/ptex/include/PtexVersion.h")
InstallDependency("/include/PtexUtils.h", "/ptex/include/PtexUtils.h")
InstallDependency("/include/Ptexture.h", "/ptex/include/Ptexture.h")
InstallDependency("/include/PtexInt.h", "/ptex/include/PtexInt.h")
InstallDependency("/include/PtexHalf.h", "/ptex/include/PtexHalf.h")
def InstallPtex_LinuxOrMacOS(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(PTEX_URL, context, force)):
RunCMake(context, force, buildArgs)
PTEX = Dependency("Ptex", InstallPtex, "include/PtexVersion.h")