-
Notifications
You must be signed in to change notification settings - Fork 4
/
buildbase.py
1538 lines (1350 loc) · 54.9 KB
/
buildbase.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
# buildbase.py はビルドスクリプトのテンプレートとなるファイル
#
# 自身のリポジトリにコピーして利用する。
#
# 元のファイルは以下のリポジトリにある:
# https://github.com/melpon/buildbase
#
# 更新する場合は以下のコマンドを利用する:
# curl -LO https://raw.githubusercontent.com/melpon/buildbase/master/buildbase.py
#
# ライセンス: Apache License 2.0
#
# Copyright 2024 melpon (Wandbox)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import filecmp
import glob
import logging
import multiprocessing
import os
import platform
import shlex
import shutil
import stat
import subprocess
import tarfile
import urllib.parse
import zipfile
from typing import Dict, List, NamedTuple, Optional
if platform.system() == "Windows":
import winreg
class ChangeDirectory(object):
def __init__(self, cwd):
self._cwd = cwd
def __enter__(self):
self._old_cwd = os.getcwd()
logging.debug(f"pushd {self._old_cwd} --> {self._cwd}")
os.chdir(self._cwd)
def __exit__(self, exctype, excvalue, trace):
logging.debug(f"popd {self._old_cwd} <-- {self._cwd}")
os.chdir(self._old_cwd)
return False
def cd(cwd):
return ChangeDirectory(cwd)
def cmd(args, **kwargs):
logging.debug(f"+{args} {kwargs}")
if "check" not in kwargs:
kwargs["check"] = True
if "resolve" in kwargs:
resolve = kwargs["resolve"]
del kwargs["resolve"]
else:
resolve = True
if resolve:
args = [shutil.which(args[0]), *args[1:]]
return subprocess.run(args, **kwargs)
# 標準出力をキャプチャするコマンド実行。シェルの `cmd ...` や $(cmd ...) と同じ
def cmdcap(args, **kwargs):
# 3.7 でしか使えない
# kwargs['capture_output'] = True
kwargs["stdout"] = subprocess.PIPE
kwargs["stderr"] = subprocess.PIPE
kwargs["encoding"] = "utf-8"
return cmd(args, **kwargs).stdout.strip()
# https://stackoverflow.com/a/2656405
def onerror(func, path, exc_info):
"""
Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)``
"""
import stat
# Is the error an access error?
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
def rm_rf(path: str):
if not os.path.exists(path):
logging.debug(f"rm -rf {path} => path not found")
return
if os.path.isfile(path) or os.path.islink(path):
os.remove(path)
logging.debug(f"rm -rf {path} => file removed")
if os.path.isdir(path):
shutil.rmtree(path, onerror=onerror)
logging.debug(f"rm -rf {path} => directory removed")
def mkdir_p(path: str):
if os.path.exists(path):
logging.debug(f"mkdir -p {path} => already exists")
return
os.makedirs(path, exist_ok=True)
logging.debug(f"mkdir -p {path} => directory created")
if platform.system() == "Windows":
PATH_SEPARATOR = ";"
else:
PATH_SEPARATOR = ":"
def add_path(path: str, is_after=False):
logging.debug(f"add_path: {path}")
if "PATH" not in os.environ:
os.environ["PATH"] = path
return
if is_after:
os.environ["PATH"] = os.environ["PATH"] + PATH_SEPARATOR + path
else:
os.environ["PATH"] = path + PATH_SEPARATOR + os.environ["PATH"]
def download(url: str, output_dir: Optional[str] = None, filename: Optional[str] = None) -> str:
if filename is None:
output_path = urllib.parse.urlparse(url).path.split("/")[-1]
else:
output_path = filename
if output_dir is not None:
output_path = os.path.join(output_dir, output_path)
if os.path.exists(output_path):
return output_path
try:
if shutil.which("curl") is not None:
cmd(["curl", "-fLo", output_path, url])
else:
cmd(["wget", "-cO", output_path, url])
except Exception:
# ゴミを残さないようにする
if os.path.exists(output_path):
os.remove(output_path)
raise
return output_path
def read_version_file(path: str) -> Dict[str, str]:
versions = {}
lines = open(path).readlines()
for line in lines:
line = line.strip()
# コメント行
if line[:1] == "#":
continue
# 空行
if len(line) == 0:
continue
[a, b] = map(lambda x: x.strip(), line.split("=", 2))
versions[a] = b.strip('"')
return versions
# dir 以下にある全てのファイルパスを、dir2 からの相対パスで返す
def enum_all_files(dir, dir2):
for root, _, files in os.walk(dir):
for file in files:
yield os.path.relpath(os.path.join(root, file), dir2)
def versioned(func):
def wrapper(version, version_file, *args, **kwargs):
if "ignore_version" in kwargs:
if kwargs.get("ignore_version"):
rm_rf(version_file)
del kwargs["ignore_version"]
if os.path.exists(version_file):
ver = open(version_file).read()
if ver.strip() == version.strip():
return
r = func(version=version, *args, **kwargs)
with open(version_file, "w") as f:
f.write(version)
return r
return wrapper
# アーカイブが単一のディレクトリに全て格納されているかどうかを調べる。
#
# 単一のディレクトリに格納されている場合はそのディレクトリ名を返す。
# そうでない場合は None を返す。
def _is_single_dir(infos, get_name, is_dir) -> Optional[str]:
# tarfile: ['path', 'path/to', 'path/to/file.txt']
# zipfile: ['path/', 'path/to/', 'path/to/file.txt']
# どちらも / 区切りだが、ディレクトリの場合、後ろに / が付くかどうかが違う
dirname = None
for info in infos:
name = get_name(info)
n = name.rstrip("/").find("/")
if n == -1:
# ルートディレクトリにファイルが存在している
if not is_dir(info):
return None
dir = name.rstrip("/")
else:
dir = name[0:n]
# ルートディレクトリに2個以上のディレクトリが存在している
if dirname is not None and dirname != dir:
return None
dirname = dir
return dirname
def is_single_dir_tar(tar: tarfile.TarFile) -> Optional[str]:
return _is_single_dir(tar.getmembers(), lambda t: t.name, lambda t: t.isdir())
def is_single_dir_zip(zip: zipfile.ZipFile) -> Optional[str]:
return _is_single_dir(zip.infolist(), lambda z: z.filename, lambda z: z.is_dir())
# 解凍した上でファイル属性を付与する
def _extractzip(z: zipfile.ZipFile, path: str):
z.extractall(path)
if platform.system() == "Windows":
return
for info in z.infolist():
if info.is_dir():
continue
filepath = os.path.join(path, info.filename)
mod = info.external_attr >> 16
if (mod & 0o120000) == 0o120000:
# シンボリックリンク
with open(filepath, "r") as f:
src = f.read()
os.remove(filepath)
with cd(os.path.dirname(filepath)):
if os.path.exists(src):
os.symlink(src, filepath)
if os.path.exists(filepath):
# 普通のファイル
os.chmod(filepath, mod & 0o777)
# zip または tar.gz ファイルを展開する。
#
# 展開先のディレクトリは {output_dir}/{output_dirname} となり、
# 展開先のディレクトリが既に存在していた場合は削除される。
#
# もしアーカイブの内容が単一のディレクトリであった場合、
# そのディレクトリは無いものとして展開される。
#
# つまりアーカイブ libsora-1.23.tar.gz の内容が
# ['libsora-1.23', 'libsora-1.23/file1', 'libsora-1.23/file2']
# であった場合、extract('libsora-1.23.tar.gz', 'out', 'libsora') のようにすると
# - out/libsora/file1
# - out/libsora/file2
# が出力される。
#
# また、アーカイブ libsora-1.23.tar.gz の内容が
# ['libsora-1.23', 'libsora-1.23/file1', 'libsora-1.23/file2', 'LICENSE']
# であった場合、extract('libsora-1.23.tar.gz', 'out', 'libsora') のようにすると
# - out/libsora/libsora-1.23/file1
# - out/libsora/libsora-1.23/file2
# - out/libsora/LICENSE
# が出力される。
def extract(file: str, output_dir: str, output_dirname: str, filetype: Optional[str] = None):
path = os.path.join(output_dir, output_dirname)
logging.info(f"Extract {file} to {path}")
if filetype == "gzip" or file.endswith(".tar.gz"):
rm_rf(path)
with tarfile.open(file) as t:
dir = is_single_dir_tar(t)
if dir is None:
os.makedirs(path, exist_ok=True)
t.extractall(path)
else:
logging.info(f"Directory {dir} is stripped")
path2 = os.path.join(output_dir, dir)
rm_rf(path2)
t.extractall(output_dir)
if path != path2:
logging.debug(f"mv {path2} {path}")
os.replace(path2, path)
elif filetype == "zip" or file.endswith(".zip"):
rm_rf(path)
with zipfile.ZipFile(file) as z:
dir = is_single_dir_zip(z)
if dir is None:
os.makedirs(path, exist_ok=True)
# z.extractall(path)
_extractzip(z, path)
else:
logging.info(f"Directory {dir} is stripped")
path2 = os.path.join(output_dir, dir)
rm_rf(path2)
# z.extractall(output_dir)
_extractzip(z, output_dir)
if path != path2:
logging.debug(f"mv {path2} {path}")
os.replace(path2, path)
else:
raise Exception("file should end with .tar.gz or .zip")
def clone_and_checkout(url, version, dir, fetch, fetch_force):
if fetch_force:
rm_rf(dir)
if not os.path.exists(os.path.join(dir, ".git")):
cmd(["git", "clone", url, dir])
fetch = True
if fetch:
with cd(dir):
cmd(["git", "fetch"])
cmd(["git", "reset", "--hard"])
cmd(["git", "clean", "-df"])
cmd(["git", "checkout", "-f", version])
def git_clone_shallow(url, hash, dir):
rm_rf(dir)
mkdir_p(dir)
with cd(dir):
cmd(["git", "init"])
cmd(["git", "remote", "add", "origin", url])
cmd(["git", "fetch", "--depth=1", "origin", hash])
cmd(["git", "reset", "--hard", "FETCH_HEAD"])
def apply_patch(patch, dir, depth):
with cd(dir):
logging.info(f"patch -p{depth} < {patch}")
if platform.system() == "Windows":
cmd(
[
"git",
"apply",
f"-p{depth}",
"--ignore-space-change",
"--ignore-whitespace",
"--whitespace=nowarn",
patch,
]
)
else:
with open(patch) as stdin:
cmd(["patch", f"-p{depth}"], stdin=stdin)
def copyfile_if_different(src, dst):
if os.path.exists(dst) and filecmp.cmp(src, dst, shallow=False):
return
shutil.copyfile(src, dst)
# NOTE(enm10k): shutil.copytree に Python 3.8 で追加された dirs_exist_ok=True を指定して使いたかったが、
# GitHub Actions の Windows のランナー (widnwos-2019) にインストールされている Python のバージョンが古くて利用できなかった
# actions/setup-python で Python 3.8 を設定してビルドしたところ、 Lyra のビルドがエラーになったためこの関数を自作した
# Windows のランナーを更新した場合は、この関数は不要になる可能性が高い
def copytree(src_dir, dst_dir):
for file_path in glob.glob(src_dir + "/**", recursive=True):
dest_path = os.path.join(dst_dir, os.path.relpath(file_path, src_dir))
if os.path.isdir(file_path):
os.makedirs(dest_path, exist_ok=True)
else:
shutil.copy2(file_path, dest_path)
def git_get_url_and_revision(dir):
with cd(dir):
rev = cmdcap(["git", "rev-parse", "HEAD"])
url = cmdcap(["git", "remote", "get-url", "origin"])
return url, rev
def replace_vcproj_static_runtime(project_file: str):
# なぜか MSVC_STATIC_RUNTIME が効かずに DLL ランタイムを使ってしまうので
# 生成されたプロジェクトに対して静的ランタイムを使うように変更する
s = open(project_file, "r", encoding="utf-8").read()
s = s.replace("MultiThreadedDLL", "MultiThreaded")
s = s.replace("MultiThreadedDebugDLL", "MultiThreadedDebug")
open(project_file, "w", encoding="utf-8").write(s)
@versioned
def install_webrtc(version, source_dir, install_dir, platform: str):
win = platform.startswith("windows_")
filename = f'webrtc.{platform}.{"zip" if win else "tar.gz"}'
rm_rf(os.path.join(source_dir, filename))
archive = download(
f"https://github.com/shiguredo-webrtc-build/webrtc-build/releases/download/{version}/{filename}",
output_dir=source_dir,
)
rm_rf(os.path.join(install_dir, "webrtc"))
extract(archive, output_dir=install_dir, output_dirname="webrtc")
def build_webrtc(platform, local_webrtc_build_dir, local_webrtc_build_args, debug):
with cd(local_webrtc_build_dir):
args = ["--webrtc-nobuild-ios-framework", "--webrtc-nobuild-android-aar"]
if debug:
args += ["--debug"]
args += local_webrtc_build_args
cmd(["python3", "run.py", "build", platform, *args])
# インクルードディレクトリを増やしたくないので、
# __config_site を libc++ のディレクトリにコピーしておく
webrtc_source_dir = os.path.join(local_webrtc_build_dir, "_source", platform, "webrtc")
src_config = os.path.join(
webrtc_source_dir, "src", "buildtools", "third_party", "libc++", "__config_site"
)
dst_config = os.path.join(
webrtc_source_dir, "src", "third_party", "libc++", "src", "include", "__config_site"
)
copyfile_if_different(src_config, dst_config)
# __assertion_handler をコピーする
src_assertion = os.path.join(
webrtc_source_dir,
"src",
"buildtools",
"third_party",
"libc++",
"__assertion_handler",
)
dst_assertion = os.path.join(
webrtc_source_dir,
"src",
"third_party",
"libc++",
"src",
"include",
"__assertion_handler",
)
copyfile_if_different(src_assertion, dst_assertion)
class WebrtcInfo(NamedTuple):
version_file: str
deps_file: str
webrtc_include_dir: str
webrtc_source_dir: Optional[str]
webrtc_library_dir: str
clang_dir: str
libcxx_dir: str
def get_webrtc_info(
platform: str, local_webrtc_build_dir: Optional[str], install_dir: str, debug: bool
) -> WebrtcInfo:
webrtc_install_dir = os.path.join(install_dir, "webrtc")
if local_webrtc_build_dir is None:
return WebrtcInfo(
version_file=os.path.join(webrtc_install_dir, "VERSIONS"),
deps_file=os.path.join(webrtc_install_dir, "DEPS"),
webrtc_include_dir=os.path.join(webrtc_install_dir, "include"),
webrtc_source_dir=None,
webrtc_library_dir=os.path.join(webrtc_install_dir, "lib"),
clang_dir=os.path.join(install_dir, "llvm", "clang"),
libcxx_dir=os.path.join(install_dir, "llvm", "libcxx"),
)
else:
webrtc_build_source_dir = os.path.join(
local_webrtc_build_dir, "_source", platform, "webrtc"
)
configuration = "debug" if debug else "release"
webrtc_build_build_dir = os.path.join(
local_webrtc_build_dir, "_build", platform, configuration, "webrtc"
)
return WebrtcInfo(
version_file=os.path.join(local_webrtc_build_dir, "VERSION"),
deps_file=os.path.join(local_webrtc_build_dir, "DEPS"),
webrtc_include_dir=os.path.join(webrtc_build_source_dir, "src"),
webrtc_source_dir=os.path.join(webrtc_build_source_dir, "src"),
webrtc_library_dir=webrtc_build_build_dir,
clang_dir=os.path.join(
webrtc_build_source_dir, "src", "third_party", "llvm-build", "Release+Asserts"
),
libcxx_dir=os.path.join(webrtc_build_source_dir, "src", "third_party", "libc++", "src"),
)
@versioned
def install_boost(version, source_dir, install_dir, sora_version, platform: str):
win = platform.startswith("windows_")
filename = (
f'boost-{version}_sora-cpp-sdk-{sora_version}_{platform}.{"zip" if win else "tar.gz"}'
)
rm_rf(os.path.join(source_dir, filename))
archive = download(
f"https://github.com/shiguredo/sora-cpp-sdk/releases/download/{sora_version}/{filename}",
output_dir=source_dir,
)
rm_rf(os.path.join(install_dir, "boost"))
extract(archive, output_dir=install_dir, output_dirname="boost")
@versioned
def build_and_install_boost(
version: str,
source_dir,
build_dir,
install_dir,
debug: bool,
cxx: str,
cflags: List[str],
cxxflags: List[str],
linkflags: List[str],
toolset,
visibility,
target_os,
architecture,
android_ndk,
native_api_level,
):
version_underscore = version.replace(".", "_")
archive = download(
f"https://boostorg.jfrog.io/artifactory/main/release/{version}/source/boost_{version_underscore}.tar.gz",
source_dir,
)
extract(archive, output_dir=build_dir, output_dirname="boost")
with cd(os.path.join(build_dir, "boost")):
bootstrap = ".\\bootstrap.bat" if target_os == "windows" else "./bootstrap.sh"
b2 = "b2" if target_os == "windows" else "./b2"
runtime_link = "static" if target_os == "windows" else "shared"
cmd([bootstrap])
if target_os == "iphone":
IOS_BUILD_TARGETS = [("arm64", "iphoneos")]
for arch, sdk in IOS_BUILD_TARGETS:
clangpp = cmdcap(["xcodebuild", "-find", "clang++"])
sysroot = cmdcap(["xcrun", "--sdk", sdk, "--show-sdk-path"])
boost_arch = "x86" if arch == "x86_64" else "arm"
with open("project-config.jam", "w") as f:
f.write(
f"using clang \
: iphone \
: {clangpp} -arch {arch} -isysroot {sysroot} \
-fembed-bitcode \
-mios-version-min=10.0 \
-fvisibility=hidden \
: <striper> <root>{sysroot} \
; \
"
)
cmd(
[
b2,
"install",
"-d+0",
f'--build-dir={os.path.join(build_dir, "boost", f"build-{arch}-{sdk}")}',
f'--prefix={os.path.join(build_dir, "boost", f"install-{arch}-{sdk}")}',
"--with-json",
"--with-filesystem",
"--layout=system",
"--ignore-site-config",
f'variant={"debug" if debug else "release"}',
f'cflags={" ".join(cflags)}',
f'cxxflags={" ".join(cxxflags)}',
f'linkflags={" ".join(linkflags)}',
f"toolset={toolset}",
f"visibility={visibility}",
f"target-os={target_os}",
"address-model=64",
"link=static",
f"runtime-link={runtime_link}",
"threading=multi",
f"architecture={boost_arch}",
]
)
arch, sdk = IOS_BUILD_TARGETS[0]
installed_path = os.path.join(build_dir, "boost", f"install-{arch}-{sdk}")
rm_rf(os.path.join(install_dir, "boost"))
cmd(["cp", "-r", installed_path, os.path.join(install_dir, "boost")])
for lib in enum_all_files(
os.path.join(installed_path, "lib"), os.path.join(installed_path, "lib")
):
if not lib.endswith(".a"):
continue
files = [
os.path.join(build_dir, "boost", f"install-{arch}-{sdk}", "lib", lib)
for arch, sdk in IOS_BUILD_TARGETS
]
if len(files) == 1:
shutil.copyfile(files[0], os.path.join(install_dir, "boost", "lib", lib))
else:
cmd(
[
"lipo",
"-create",
"-output",
os.path.join(install_dir, "boost", "lib", lib),
]
+ files
)
elif target_os == "android":
# Android の場合、android-ndk を使ってビルドする
with open("project-config.jam", "w") as f:
bin = os.path.join(
android_ndk, "toolchains", "llvm", "prebuilt", "linux-x86_64", "bin"
)
sysroot = os.path.join(
android_ndk, "toolchains", "llvm", "prebuilt", "linux-x86_64", "sysroot"
)
f.write(
f"using clang \
: android \
: {os.path.join(bin, 'clang++')} \
--target=aarch64-none-linux-android{native_api_level} \
--sysroot={sysroot} \
: <archiver>{os.path.join(bin, 'llvm-ar')} \
<ranlib>{os.path.join(bin, 'llvm-ranlib')} \
; \
"
)
cmd(
[
b2,
"install",
"-d+0",
f'--prefix={os.path.join(install_dir, "boost")}',
"--with-json",
"--with-filesystem",
"--layout=system",
"--ignore-site-config",
f'variant={"debug" if debug else "release"}',
f"compileflags=--sysroot={sysroot}",
f'cflags={" ".join(cflags)}',
f'cxxflags={" ".join(cxxflags)}',
f'linkflags={" ".join(linkflags)}',
f"toolset={toolset}",
f"visibility={visibility}",
f"target-os={target_os}",
"address-model=64",
"link=static",
f"runtime-link={runtime_link}",
"threading=multi",
"architecture=arm",
]
)
else:
if len(cxx) != 0:
with open("project-config.jam", "w") as f:
f.write(f"using {toolset} : : {cxx} : ;")
cmd(
[
b2,
"install",
"-d+0",
f'--prefix={os.path.join(install_dir, "boost")}',
"--with-json",
"--with-filesystem",
"--layout=system",
"--ignore-site-config",
f'variant={"debug" if debug else "release"}',
f'cflags={" ".join(cflags)}',
f'cxxflags={" ".join(cxxflags)}',
f'linkflags={" ".join(linkflags)}',
f"toolset={toolset}",
f"visibility={visibility}",
f"target-os={target_os}",
"address-model=64",
"link=static",
f"runtime-link={runtime_link}",
"threading=multi",
f"architecture={architecture}",
]
)
@versioned
def install_sora(version, source_dir, install_dir, platform: str):
win = platform.startswith("windows_")
filename = f'sora-cpp-sdk-{version}_{platform}.{"zip" if win else "tar.gz"}'
rm_rf(os.path.join(source_dir, filename))
archive = download(
f"https://github.com/shiguredo/sora-cpp-sdk/releases/download/{version}/{filename}",
output_dir=source_dir,
)
rm_rf(os.path.join(install_dir, "sora"))
extract(archive, output_dir=install_dir, output_dirname="sora")
def install_sora_and_deps(platform: str, source_dir: str, install_dir: str):
version = read_version_file("VERSION")
# Boost
install_boost_args = {
"version": version["BOOST_VERSION"],
"version_file": os.path.join(install_dir, "boost.version"),
"source_dir": source_dir,
"install_dir": install_dir,
"sora_version": version["SORA_CPP_SDK_VERSION"],
"platform": platform,
}
install_boost(**install_boost_args)
# Sora C++ SDK
install_sora_args = {
"version": version["SORA_CPP_SDK_VERSION"],
"version_file": os.path.join(install_dir, "sora.version"),
"source_dir": source_dir,
"install_dir": install_dir,
"platform": platform,
}
install_sora(**install_sora_args)
def build_sora(
platform: str,
local_sora_cpp_sdk_dir: str,
local_sora_cpp_sdk_args: List[str],
debug: bool,
local_webrtc_build_dir: Optional[str],
):
if debug and "--debug" not in local_sora_cpp_sdk_args:
local_sora_cpp_sdk_args = ["--debug", *local_sora_cpp_sdk_args]
if local_webrtc_build_dir is not None:
local_sora_cpp_sdk_args = [
"--local-webrtc-build-dir",
local_webrtc_build_dir,
*local_sora_cpp_sdk_args,
]
with cd(local_sora_cpp_sdk_dir):
cmd(["python3", "run.py", platform, *local_sora_cpp_sdk_args])
class SoraInfo(NamedTuple):
sora_install_dir: str
boost_install_dir: str
def get_sora_info(
platform: str, local_sora_cpp_sdk_dir: Optional[str], install_dir: str, debug: bool
) -> SoraInfo:
if local_sora_cpp_sdk_dir is not None:
configuration = "debug" if debug else "release"
install_dir = os.path.join(local_sora_cpp_sdk_dir, "_install", platform, configuration)
return SoraInfo(
sora_install_dir=os.path.join(install_dir, "sora"),
boost_install_dir=os.path.join(install_dir, "boost"),
)
@versioned
def install_rootfs(version, install_dir, conf):
rootfs_dir = os.path.join(install_dir, "rootfs")
rm_rf(rootfs_dir)
cmd(["multistrap", "--no-auth", "-a", "arm64", "-d", rootfs_dir, "-f", conf])
# 絶対パスのシンボリックリンクを相対パスに置き換えていく
for dir, _, filenames in os.walk(rootfs_dir):
for filename in filenames:
linkpath = os.path.join(dir, filename)
# symlink かどうか
if not os.path.islink(linkpath):
continue
target = os.readlink(linkpath)
# 絶対パスかどうか
if not os.path.isabs(target):
continue
# rootfs_dir を先頭に付けることで、
# rootfs の外から見て正しい絶対パスにする
targetpath = rootfs_dir + target
# 参照先の絶対パスが存在するかどうか
if not os.path.exists(targetpath):
continue
# 相対パスに置き換える
relpath = os.path.relpath(targetpath, dir)
logging.debug(f"{linkpath[len(rootfs_dir):]} targets {target} to {relpath}")
os.remove(linkpath)
os.symlink(relpath, linkpath)
# なぜかシンボリックリンクが登録されていないので作っておく
link = os.path.join(rootfs_dir, "usr", "lib", "aarch64-linux-gnu", "tegra", "libnvbuf_fdmap.so")
file = os.path.join(
rootfs_dir, "usr", "lib", "aarch64-linux-gnu", "tegra", "libnvbuf_fdmap.so.1.0.0"
)
if os.path.exists(file) and not os.path.exists(link):
os.symlink(os.path.basename(file), link)
@versioned
def install_android_ndk(version, install_dir, source_dir):
archive = download(
f"https://dl.google.com/android/repository/android-ndk-{version}-linux.zip", source_dir
)
rm_rf(os.path.join(install_dir, "android-ndk"))
extract(archive, output_dir=install_dir, output_dirname="android-ndk")
@versioned
def install_android_sdk_cmdline_tools(version, install_dir, source_dir):
archive = download(
f"https://dl.google.com/android/repository/commandlinetools-linux-{version}_latest.zip",
source_dir,
)
tools_dir = os.path.join(install_dir, "android-sdk-cmdline-tools")
rm_rf(tools_dir)
extract(archive, output_dir=tools_dir, output_dirname="cmdline-tools")
sdkmanager = os.path.join(tools_dir, "cmdline-tools", "bin", "sdkmanager")
# ライセンスを許諾する
cmd(["/bin/bash", "-c", f"yes | {sdkmanager} --sdk_root={tools_dir} --licenses"])
@versioned
def install_llvm(
version,
install_dir,
tools_url,
tools_commit,
libcxx_url,
libcxx_commit,
buildtools_url,
buildtools_commit,
):
llvm_dir = os.path.join(install_dir, "llvm")
rm_rf(llvm_dir)
mkdir_p(llvm_dir)
with cd(llvm_dir):
# tools の update.py を叩いて特定バージョンの clang バイナリを拾う
git_clone_shallow(tools_url, tools_commit, "tools")
with cd("tools"):
cmd(
[
"python3",
os.path.join("clang", "scripts", "update.py"),
"--output-dir",
os.path.join(llvm_dir, "clang"),
]
)
# 特定バージョンの libcxx を利用する
git_clone_shallow(libcxx_url, libcxx_commit, "libcxx")
# __config_site のために特定バージョンの buildtools を取得する
git_clone_shallow(buildtools_url, buildtools_commit, "buildtools")
with cd("buildtools"):
cmd(["git", "reset", "--hard", buildtools_commit])
shutil.copyfile(
os.path.join(llvm_dir, "buildtools", "third_party", "libc++", "__config_site"),
os.path.join(llvm_dir, "libcxx", "include", "__config_site"),
)
# __assertion_handler をコピーする
# 背景: https://source.chromium.org/chromium/_/chromium/external/github.com/llvm/llvm-project/libcxx.git/+/1e5bda0d1ce8e346955aa4a85eaab258785f11f7
shutil.copyfile(
# NOTE(enm10k): 最初は default_assertion_handler.in をコピーしていたが、 buildtools 以下に
# default_assertion_handler.in から生成されたと思われる __assertion_handler が存在するため、それをコピーする
# os.path.join(llvm_dir, "libcxx", "vendor", "llvm", "default_assertion_handler.in"),
os.path.join(llvm_dir, "buildtools", "third_party", "libc++", "__assertion_handler"),
os.path.join(llvm_dir, "libcxx", "include", "__assertion_handler"),
)
def cmake_path(path: str) -> str:
return path.replace("\\", "/")
@versioned
def install_cmake(version, source_dir, install_dir, platform: str, ext):
url = f"https://github.com/Kitware/CMake/releases/download/v{version}/cmake-{version}-{platform}.{ext}"
path = download(url, source_dir)
extract(path, install_dir, "cmake")
# Android で自前の CMake を利用する場合、ninja へのパスが見つけられない問題があるので、同じディレクトリに symlink を貼る
# https://issuetracker.google.com/issues/206099937
if platform.startswith("linux"):
with cd(os.path.join(install_dir, "cmake", "bin")):
cmd(["ln", "-s", "/usr/bin/ninja", "ninja"])
@versioned
def install_sdl2(
version, source_dir, build_dir, install_dir, debug: bool, platform: str, cmake_args: List[str]
):
url = f"http://www.libsdl.org/release/SDL2-{version}.zip"
path = download(url, source_dir)
sdl2_source_dir = os.path.join(source_dir, "sdl2")
sdl2_build_dir = os.path.join(build_dir, "sdl2")
sdl2_install_dir = os.path.join(install_dir, "sdl2")
rm_rf(sdl2_source_dir)
rm_rf(sdl2_build_dir)
rm_rf(sdl2_install_dir)
extract(path, source_dir, "sdl2")
mkdir_p(sdl2_build_dir)
with cd(sdl2_build_dir):
configuration = "Debug" if debug else "Release"
cmake_args = cmake_args[:]
cmake_args += [
sdl2_source_dir,
f"-DCMAKE_BUILD_TYPE={configuration}",
f"-DCMAKE_INSTALL_PREFIX={cmake_path(sdl2_install_dir)}",
"-DBUILD_SHARED_LIBS=OFF",
]
if platform == "windows":
cmake_args += [
"-G",
"Visual Studio 16 2019",
"-DSDL_FORCE_STATIC_VCRT=ON",
"-DHAVE_LIBC=ON",
]
elif platform == "macos":
# システムでインストール済みかによって ON/OFF が切り替わってしまうため、
# どの環境でも同じようにインストールされるようにするため全部 ON/OFF を明示的に指定する
cmake_args += [
"-DSDL_ATOMIC=OFF",
"-DSDL_AUDIO=OFF",
"-DSDL_VIDEO=ON",
"-DSDL_RENDER=ON",
"-DSDL_EVENTS=ON",
"-DSDL_JOYSTICK=ON",
"-DSDL_HAPTIC=ON",
"-DSDL_POWER=ON",
"-DSDL_THREADS=ON",
"-DSDL_TIMERS=OFF",
"-DSDL_FILE=OFF",
"-DSDL_LOADSO=ON",
"-DSDL_CPUINFO=OFF",
"-DSDL_FILESYSTEM=OFF",
"-DSDL_SENSOR=ON",
"-DSDL_OPENGL=ON",
"-DSDL_OPENGLES=ON",
"-DSDL_RPI=OFF",
"-DSDL_WAYLAND=OFF",
"-DSDL_X11=OFF",
"-DSDL_VULKAN=OFF",
"-DSDL_VIVANTE=OFF",
"-DSDL_COCOA=ON",
"-DSDL_METAL=ON",
"-DSDL_KMSDRM=OFF",
]
elif platform == "linux":
# システムでインストール済みかによって ON/OFF が切り替わってしまうため、
# どの環境でも同じようにインストールされるようにするため全部 ON/OFF を明示的に指定する
cmake_args += [
"-DSDL_ATOMIC=OFF",
"-DSDL_AUDIO=OFF",
"-DSDL_VIDEO=ON",
"-DSDL_RENDER=ON",
"-DSDL_EVENTS=ON",
"-DSDL_JOYSTICK=ON",
"-DSDL_HAPTIC=ON",
"-DSDL_POWER=ON",
"-DSDL_THREADS=ON",
"-DSDL_TIMERS=OFF",
"-DSDL_FILE=OFF",
"-DSDL_LOADSO=ON",
"-DSDL_CPUINFO=OFF",
"-DSDL_FILESYSTEM=OFF",
"-DSDL_SENSOR=ON",
"-DSDL_OPENGL=ON",
"-DSDL_OPENGLES=ON",
"-DSDL_RPI=OFF",
"-DSDL_WAYLAND=OFF",