-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathbuildtools.py
More file actions
2105 lines (1671 loc) · 68.6 KB
/
Copy pathbuildtools.py
File metadata and controls
2105 lines (1671 loc) · 68.6 KB
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/python3
from __future__ import annotations
import argparse
import os
import re
import shlex
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import urllib.request
import zipfile
from pathlib import Path
from typing import Callable, Iterable, Mapping, NotRequired, Sequence, TypedDict
EnvMap = dict[str, str]
FlagMap = dict[str, int]
class ValidationTarget(TypedDict):
platform: str
target: str
config: str
compiler: NotRequired[str]
run_target: NotRequired[str]
def make_flag_map(*enabled_flag_names: str) -> FlagMap:
return {flag_name: 1 for flag_name in enabled_flag_names}
def make_validation_target(
platform_name: str,
target_name: str,
config_name: str,
compiler_name: str | None = None,
run_target_name: str | None = None,
) -> ValidationTarget:
validation_target: ValidationTarget = {
'platform': platform_name,
'target': target_name,
'config': config_name,
}
if compiler_name is not None:
validation_target['compiler'] = compiler_name
if run_target_name is not None:
validation_target['run_target'] = run_target_name
return validation_target
def make_validation_target_set(
name_prefix: str,
platform_name: str,
target_names: Sequence[str],
config_name: str = 'Debug',
compiler_name: str | None = None,
) -> dict[str, ValidationTarget]:
return {
f'{name_prefix}-{target_name}': make_validation_target(
platform_name,
target_name,
config_name,
compiler_name=compiler_name,
)
for target_name in target_names
}
FLAG_NAMES = [
'FO_BUILD_CLIENT',
'FO_BUILD_SERVER',
'FO_BUILD_EDITOR',
'FO_BUILD_MAPPER',
'FO_BUILD_ASCOMPILER',
'FO_BUILD_BAKER',
'FO_UNIT_TESTS',
'FO_CODE_COVERAGE',
]
COMMON_VALIDATION_TARGET_NAMES = ('client', 'server', 'editor', 'mapper', 'ascompiler', 'baker')
WIN64_CLANG_VALIDATION_TARGET_NAMES = ('client', 'server', 'ascompiler', 'baker')
SINGLE_FLAG_BUILD_TARGETS = {
'client': 'FO_BUILD_CLIENT',
'server': 'FO_BUILD_SERVER',
'editor': 'FO_BUILD_EDITOR',
'mapper': 'FO_BUILD_MAPPER',
'ascompiler': 'FO_BUILD_ASCOMPILER',
'baker': 'FO_BUILD_BAKER',
'unit-tests': 'FO_UNIT_TESTS',
'code-coverage': 'FO_CODE_COVERAGE',
}
SINGLE_CLIENT_VALIDATION_PLATFORMS = {
'android-arm32': 'android-arm32',
'android-arm64': 'android-arm64',
'android-x86': 'android-x86',
'web': 'web',
'mac': 'mac',
'ios': 'ios',
'win32': 'win32',
}
BUILD_TARGETS: dict[str, FlagMap] = {
**{target_name: make_flag_map(flag_name) for target_name, flag_name in SINGLE_FLAG_BUILD_TARGETS.items()},
'toolset': make_flag_map('FO_BUILD_ASCOMPILER', 'FO_BUILD_BAKER'),
'full': make_flag_map(
'FO_BUILD_CLIENT',
'FO_BUILD_SERVER',
'FO_BUILD_EDITOR',
'FO_BUILD_MAPPER',
'FO_BUILD_ASCOMPILER',
'FO_BUILD_BAKER',
),
}
VALIDATION_TARGETS: dict[str, ValidationTarget] = {
**make_validation_target_set('linux', 'linux', COMMON_VALIDATION_TARGET_NAMES),
**make_validation_target_set('linux-gcc', 'linux', COMMON_VALIDATION_TARGET_NAMES, compiler_name='gcc'),
**{
f'{name_prefix}-client': make_validation_target(platform_name, 'client', 'Debug')
for name_prefix, platform_name in SINGLE_CLIENT_VALIDATION_PLATFORMS.items()
},
**make_validation_target_set('win64', 'win64', COMMON_VALIDATION_TARGET_NAMES),
**make_validation_target_set('win64-clang', 'win64-clang', WIN64_CLANG_VALIDATION_TARGET_NAMES),
'unit-tests': make_validation_target('linux', 'unit-tests', 'Debug', run_target_name='RunUnitTests'),
'code-coverage': make_validation_target('linux', 'code-coverage', 'Debug', compiler_name='gcc', run_target_name='RunCodeCoverage'),
}
ANDROID_PLATFORMS = ('android-arm32', 'android-arm64', 'android-x86')
APPLE_PLATFORMS = ('mac', 'ios')
ANDROID_ABI_BY_PLATFORM = {
'android-arm32': 'armeabi-v7a',
'android-arm64': 'arm64-v8a',
'android-x86': 'x86',
}
WINDOWS_BUILD_BY_PLATFORM = {
'win32': ('Win32', None),
'win64': ('x64', None),
'win32-clang': ('Win32', 'ClangCL'),
'win64-clang': ('x64', 'ClangCL'),
}
FORMAT_PATTERNS = [
'**/*.cpp',
'**/*.h',
'**/*.fos',
]
UTF8_BOM = b'\xef\xbb\xbf'
CLANG_FORMAT_VERSION_RE = re.compile(r'clang-format version (\d+)(?:\.|\b)')
XWIN_SPLAT_ARCHES = ('x86', 'x86_64')
XWIN_ARCH_LIB_PARENT_DIRS = (Path('crt/lib'), Path('sdk/lib/um'), Path('sdk/lib/ucrt'))
XWIN_HTTP_RETRY_COUNT = '5'
# clang-format treats `?` as a binary operator and inserts whitespace around
# it: `Critter? cr` becomes `Critter ? cr`. AngelScript uses `T?` as a
# nullable type suffix (parsed natively by the engine since the
# `asBC_RefCpyChk` change) and the project style is to keep `?` attached to
# the type. The same regex is used by `Tools/Formatter/format_project.py`
# in the embedding project; keep them in sync if the suffix shape changes.
# The type token is either an uppercase identifier with optional namespace
# and optional `[]` (covers `Critter`, `Critter[]`, `TutorialSystem::Point`,
# etc.) or a lowercase primitive followed by `[]` (covers `hstring[]`,
# `int[]`, `string[]` â€" array-of-primitive is itself a handle and can carry
# `?`, but the bare primitive cannot, so the `[]` is mandatory here).
_FOS_NULLABLE_TYPE = r'(?:[A-Z][\w:]*(?:\[\])?|[a-z][\w]*\[\])'
FOS_NULLABLE_SUFFIX_RE = re.compile(
r'(?<![.\w])(' + _FOS_NULLABLE_TYPE + r')\s+\?\s+([A-Za-z_]\w*)(\s*(?:[(,)=;]|\[\]))'
)
# Inside function bodies we also need to repair uninitialized declarations
# `Critter ? targetCr;` â€" the trailing `;` (no `=`) form. A ternary always
# carries `:` between its branches and never `;` directly after the candidate
# identifier, so adding `;` here doesn't collide with ternary parsing.
FOS_NULLABLE_SUFFIX_BODY_RE = re.compile(
r'(?<![.\w])(' + _FOS_NULLABLE_TYPE + r')\s+\?\s+([A-Za-z_]\w*)(\s*[=;])'
)
# clang-format also mangles the nullable marker inside template / cast angle
# brackets (`cast<MovePlan?>(x)` -> `cast < MovePlan ? > (x)`), the bracket
# nullable-element array (`Item?[]` -> `Item ? []`), and named call arguments
# (`foo(name: v)` -> `foo(name : v)`). A `?` immediately before `>` or an empty
# `[]`, and a `:` whose left side is an argument-position identifier, are all
# unambiguous markers, so the inserted spacing is collapsed back. String / char
# literals and comments are masked first so literal text is never rewritten. Kept
# in sync with `Tools/Formatter/format_project.py` in the embedding project.
_FOS_ANGLE_NAME = r'(?:cast|[A-Za-z_]\w*)'
_FOS_ANGLE_SUBTYPE = r'[\w:]+(?:\s*\[\s*\])?'
FOS_NULLABLE_ANGLE_CALL_RE = re.compile(
r'\b(' + _FOS_ANGLE_NAME + r')\s*<\s*(' + _FOS_ANGLE_SUBTYPE + r')\s*\?\s*>\s*\('
)
FOS_NULLABLE_ANGLE_RE = re.compile(
r'\b(' + _FOS_ANGLE_NAME + r')\s*<\s*(' + _FOS_ANGLE_SUBTYPE + r')\s*\?\s*>'
)
FOS_NULLABLE_BRACKET_RE = re.compile(r'\b([A-Z][\w:]*)\s*\?\s*\[\s*\]')
FOS_NAMED_ARG_RE = re.compile(r'([(,]\s*[A-Za-z_]\w*)\s+:(?!:)')
FOS_LITERAL_OR_COMMENT_RE = re.compile(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|//[^\n]*|/\*.*?\*/', re.DOTALL)
FOS_STASH_RE = re.compile('\x00(\\d+)\x00')
def _fos_collapse_nullable_angle(match: 're.Match[str]', suffix: str) -> str:
return match.group(1) + '<' + re.sub(r'\s+', '', match.group(2)) + '?>' + suffix
LINUX_PACKAGE_GROUPS = {
'common-packages': (
'10',
['clang-20', 'clang-format-20', 'build-essential', 'git', 'cmake', 'python3', 'python3-pytest', 'wget', 'unzip', 'binutils-dev'],
),
'linux-packages': (
'7',
['libc++-dev', 'libc++abi-dev', 'libx11-dev', 'libxcursor-dev', 'libxrandr-dev', 'libxss-dev', 'libxtst-dev', 'libjack-dev', 'libpulse-dev', 'libasound-dev', 'freeglut3-dev', 'libssl-dev', 'libevent-dev', 'libxi-dev', 'libzstd-dev'],
),
'web-packages': (
'2',
['nodejs', 'default-jre'],
),
'android-packages': (
'3',
['openjdk-17-jdk'],
),
'windows-cross-packages': (
'3',
['lld-20', 'llvm-20', 'clang-tools-20', 'cabextract'],
),
}
ANDROID_REQUIRED_SDK_PACKAGES = (
'platform-tools',
'build-tools;34.0.0',
'platforms;android-35',
)
def log(*parts: object) -> None:
print('[BuildTools]', *parts, flush=True)
class TerminalProgress:
def __init__(self, prefix: str) -> None:
self._prefix = prefix
self._last_len = 0
def update(self, message: str) -> None:
line = f'[{self._prefix}] {message}'
padding = ' ' * max(0, self._last_len - len(line))
print('\r' + line + padding, end='', flush=True)
self._last_len = len(line)
def clear(self) -> None:
if self._last_len == 0:
return
print('\r' + ' ' * self._last_len + '\r', end='', flush=True)
self._last_len = 0
def finish(self, message: str) -> None:
self.clear()
print(f'[{self._prefix}] {message}', flush=True)
def read_first_line(path: Path) -> str:
if not path.is_file():
return ''
with path.open('r', encoding='utf-8-sig') as file:
return file.readline().strip()
def resolve_buildtools_path(env: Mapping[str, str], *parts: str) -> Path:
return Path(env['FO_ENGINE_ROOT']) / 'BuildTools' / Path(*parts)
def resolve_buildtools_cmake_path(env: Mapping[str, str], file_name: str) -> Path:
return resolve_buildtools_path(env, 'cmake', file_name)
def resolve_validation_project_source(env: Mapping[str, str]) -> Path:
return resolve_buildtools_path(env, 'validation-project')
def resolve_workspace_path(env: Mapping[str, str], *parts: str) -> Path:
return Path(env['FO_WORKSPACE']) / Path(*parts)
def resolve_toolset_build_dir(env: Mapping[str, str]) -> Path:
build_dir_name = 'build-win64-toolset' if os.name == 'nt' else 'build-linux-toolset'
return resolve_workspace_path(env, build_dir_name)
def resolve_web_debug_root(env: Mapping[str, str]) -> Path:
return resolve_workspace_path(env, 'web-debug')
def resolve_web_package_dir(env: Mapping[str, str], devname: str, config: str) -> Path:
return resolve_web_debug_root(env) / f'{devname}-Client-{config}-Web'
def resolve_configure_build_dir(env: Mapping[str, str], platform_name: str, target_name: str, config: str) -> Path:
return resolve_workspace_path(env, f'build-{platform_name}-{target_name}-{config}')
def resolve_validation_project_workspace(env: Mapping[str, str]) -> Path:
return resolve_workspace_path(env, 'validation-project')
def resolve_validation_build_dir(env: Mapping[str, str], name: str) -> Path:
return resolve_workspace_path(env, f'validate-{name}')
def resolve_workspace_emsdk_root(workspace: Path) -> str:
emsdk_root = workspace / 'emsdk'
return str(emsdk_root) if emsdk_root.is_dir() else ''
def resolve_workspace_android_sdk_root(workspace: Path) -> str:
android_sdk_root = workspace / 'android-sdk'
return str(android_sdk_root) if android_sdk_root.is_dir() else ''
def resolve_android_sdk_host_tag() -> str:
if os.name == 'nt':
return 'win'
if sys.platform == 'darwin':
return 'mac'
return 'linux'
def resolve_emscripten_toolchain(env: Mapping[str, str]) -> Path:
return Path(env['FO_EMSDK']) / 'upstream' / 'emscripten' / 'cmake' / 'Modules' / 'Platform' / 'Emscripten.cmake'
def resolve_apple_cmake() -> str:
return shutil.which('cmake') or '/Applications/CMake.app/Contents/bin/cmake'
def make_cmake_build_cmd(
config: str,
target_name: str | None = None,
cmake_bin: str = 'cmake',
env: Mapping[str, str] | None = None,
) -> list[str]:
command = [cmake_bin, '--build', '.', '--config', config]
if target_name is not None:
command.extend(['--target', target_name])
# CMake `--parallel` without a value translates to `make -j` (unbounded) for the Unix Makefiles
# generator and ignores CMAKE_BUILD_PARALLEL_LEVEL. Always pick an explicit number so callers
# that need a memory-safe cap (e.g. GCC Debug on small CI runners) can set it via env.
env_for_lookup = env if env is not None else os.environ
parallel_jobs = env_for_lookup.get('CMAKE_BUILD_PARALLEL_LEVEL')
if not parallel_jobs:
parallel_jobs = str(os.cpu_count() or 1)
command.extend(['--parallel', parallel_jobs])
return command
def run_cmake_build(build_dir: Path, config: str, env: Mapping[str, str] | None = None) -> None:
run(make_cmake_build_cmd(config, env=env), cwd=build_dir, env=env)
def run_cmake_target(build_dir: Path, config: str, target_name: str, env: Mapping[str, str] | None = None) -> None:
run(make_cmake_build_cmd(config, target_name=target_name, env=env), cwd=build_dir, env=env)
def run_emsdk_cmake_build(workspace: Path, build_dir: Path, config: str) -> None:
run_in_emsdk_env(make_cmake_build_cmd(config), workspace, cwd=build_dir)
def stringify_args(*args: object) -> list[str]:
return [str(arg) for arg in args]
def to_cmake_path(path: str | Path) -> str:
return str(path).replace('\\', '/')
def make_unix_makefiles_configure_cmd(*args: object) -> list[str]:
return ['cmake', '-G', 'Unix Makefiles', *stringify_args(*args)]
def make_emsdk_configure_cmd(toolchain_file: Path, *args: object) -> list[str]:
configure_cmd = ['cmake', '-DCMAKE_TOOLCHAIN_FILE=' + to_cmake_path(toolchain_file), *stringify_args(*args)]
if os.name == 'nt':
configure_cmd[1:1] = ['-G', 'Ninja Multi-Config', f'-DCMAKE_MAKE_PROGRAM={discover_windows_ninja()}']
else:
configure_cmd[1:1] = ['-G', 'Unix Makefiles']
return configure_cmd
def make_android_configure_cmd(toolchain_file: str, toolchain_settings: Sequence[str], *args: object) -> list[str]:
return make_unix_makefiles_configure_cmd(f'-DCMAKE_TOOLCHAIN_FILE={to_cmake_path(toolchain_file)}', *toolchain_settings, *args)
def make_xcode_configure_cmd(cmake_bin: str, *args: object) -> list[str]:
return [cmake_bin, '-G', 'Xcode', *stringify_args(*args)]
def make_windows_configure_cmd(platform_name: str, *args: object) -> list[str]:
arch, toolset = resolve_windows_build(platform_name)
configure_cmd = ['cmake', '-A', arch]
if toolset:
configure_cmd += ['-T', toolset]
configure_cmd += stringify_args(*args)
return configure_cmd
WINDOWS_CROSS_ARCH_BY_PLATFORM = {
'win32': 'x86',
'win64': 'x86_64',
'winarm64': 'aarch64',
}
def resolve_windows_cross_toolchain(env: Mapping[str, str]) -> Path:
return resolve_buildtools_path(env, 'cmake', 'toolchains', 'windows-cross.cmake')
def make_windows_cross_configure_cmd(platform_name: str, env: Mapping[str, str], *args: object) -> list[str]:
system_processor = WINDOWS_CROSS_ARCH_BY_PLATFORM.get(platform_name)
if system_processor is None:
raise SystemExit(f'Unsupported windows-cross platform: {platform_name}')
if not env.get('FO_XWIN_ROOT'):
raise SystemExit('FO_XWIN_ROOT is not set. Run prepare-workspace.sh windows-cross to splat the Windows SDK.')
toolchain = resolve_windows_cross_toolchain(env)
return [
'cmake',
'-G', 'Ninja',
f'-DCMAKE_TOOLCHAIN_FILE={to_cmake_path(toolchain)}',
f'-DCMAKE_SYSTEM_PROCESSOR={system_processor}',
*stringify_args(*args),
]
def resolve_env() -> EnvMap:
script_dir = Path(__file__).resolve().parent
project_root = Path(os.environ.get('FO_PROJECT_ROOT') or Path.cwd()).resolve()
engine_root = Path(os.environ.get('FO_ENGINE_ROOT') or (script_dir / '..')).resolve()
workspace = Path(os.environ.get('FO_WORKSPACE') or (Path.cwd() / 'Workspace')).resolve()
output = Path(os.environ.get('FO_OUTPUT') or (workspace / 'output')).resolve()
binary_output_postfix = os.environ.get('FO_BINARY_OUTPUT_POSTFIX', '')
third_party = engine_root / 'ThirdParty'
env: EnvMap = {
'FO_PROJECT_ROOT': str(project_root),
'FO_ENGINE_ROOT': str(engine_root),
'FO_WORKSPACE': str(workspace),
'FO_OUTPUT': str(output),
'FO_BINARY_OUTPUT_POSTFIX': binary_output_postfix,
'FO_EMSDK': resolve_workspace_emsdk_root(workspace),
'FO_EMSCRIPTEN_VERSION': read_first_line(third_party / 'emscripten'),
'FO_ANDROID_NDK_VERSION': read_first_line(third_party / 'android-ndk'),
'FO_ANDROID_SDK_VERSION': read_first_line(third_party / 'android-sdk'),
'FO_ANDROID_NATIVE_API_LEVEL_NUMBER': read_first_line(third_party / 'android-api'),
'FO_DOTNET_RUNTIME': read_first_line(third_party / 'dotnet-runtime'),
'FO_IOS_SDK': read_first_line(third_party / 'iOS-sdk'),
'FO_XWIN_VERSION': read_first_line(third_party / 'xwin'),
}
xwin_root = workspace / 'xwin'
env['FO_XWIN_ROOT'] = str(xwin_root) if xwin_root.is_dir() else os.environ.get('FO_XWIN_ROOT', '')
workspace_android_sdk = resolve_workspace_android_sdk_root(workspace)
if workspace_android_sdk:
env['FO_ANDROID_HOME'] = workspace_android_sdk
env['FO_ANDROID_SDK_ROOT'] = workspace_android_sdk
elif 'FO_ANDROID_HOME' not in os.environ and 'FO_ANDROID_SDK_ROOT' not in os.environ and Path('/usr/lib/android-sdk').is_dir():
env['FO_ANDROID_HOME'] = '/usr/lib/android-sdk'
env['FO_ANDROID_SDK_ROOT'] = '/usr/lib/android-sdk'
else:
env['FO_ANDROID_HOME'] = os.environ.get('FO_ANDROID_HOME', '')
env['FO_ANDROID_SDK_ROOT'] = os.environ.get('FO_ANDROID_SDK_ROOT', '')
ndk_root = workspace / 'android-ndk'
dotnet_runtime_root = workspace / 'dotnet' / 'runtime'
env['FO_ANDROID_NDK_ROOT'] = str(ndk_root) if ndk_root.is_dir() else os.environ.get('FO_ANDROID_NDK_ROOT', '')
env['FO_DOTNET_RUNTIME_ROOT'] = os.environ.get('FO_DOTNET_RUNTIME_ROOT') or (str(dotnet_runtime_root) if dotnet_runtime_root.is_dir() else '')
return env
def discover_fomain(project_root: Path) -> Path:
"""Find the single *.fomain file in the project root."""
candidates = list(project_root.glob('*.fomain'))
assert len(candidates) == 1, f'Expected exactly one .fomain file in {project_root}, found {len(candidates)}'
return candidates[0]
def apply_env(env: Mapping[str, str]) -> None:
for key, value in env.items():
if value:
os.environ[key] = value
def print_env_summary(env: Mapping[str, str]) -> None:
log('Setup environment')
for key in [
'FO_PROJECT_ROOT',
'FO_ENGINE_ROOT',
'FO_WORKSPACE',
'FO_OUTPUT',
'FO_BINARY_OUTPUT_POSTFIX',
'FO_EMSDK',
'FO_EMSCRIPTEN_VERSION',
'FO_ANDROID_HOME',
'FO_ANDROID_SDK_ROOT',
'FO_ANDROID_NDK_VERSION',
'FO_ANDROID_SDK_VERSION',
'FO_ANDROID_NATIVE_API_LEVEL_NUMBER',
'FO_ANDROID_NDK_ROOT',
'FO_DOTNET_RUNTIME',
'FO_DOTNET_RUNTIME_ROOT',
'FO_IOS_SDK',
'FO_XWIN_VERSION',
'FO_XWIN_ROOT',
]:
log('-', f'{key}={env.get(key, "")}')
def emit_shell_env(env: Mapping[str, str], shell_name: str) -> None:
for key, value in env.items():
value = value.replace('\n', ' ')
if shell_name == 'bash':
escaped = value.replace('\\', '\\\\').replace('"', '\\"')
print(f'export {key}="{escaped}"')
elif shell_name == 'cmd':
escaped = value.replace('"', '""')
print(f'set "{key}={escaped}"')
else:
print(f'{key}={value}')
def resolve_macos_cmake() -> str:
path = shutil.which('cmake')
if path:
return path
bundle_path = Path('/Applications/CMake.app/Contents/bin/cmake')
return str(bundle_path) if bundle_path.is_file() else ''
def resolve_vswhere() -> str:
roots = [
Path(os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)')),
Path(os.environ.get('ProgramFiles', r'C:\Program Files')),
]
for root in roots:
candidate = root / 'Microsoft Visual Studio' / 'Installer' / 'vswhere.exe'
if candidate.is_file():
return str(candidate)
return ''
def has_windows_build_tools() -> bool:
vswhere = resolve_vswhere()
if not vswhere:
return False
try:
output = run_capture_text([
vswhere,
'-latest',
'-products',
'*',
'-requires',
'Microsoft.VisualStudio.Component.VC.Tools.x86.x64',
'-property',
'installationPath',
])
return bool(output)
except Exception:
return False
def check_linux_host_tools() -> list[str]:
issues: list[str] = []
if not shutil.which('cmake'):
issues.append('Please install CMake')
return issues
def check_macos_host_tools() -> list[str]:
issues: list[str] = []
try:
run_capture_text(['xcode-select', '-p'])
except Exception:
issues.append('Please install Xcode from AppStore')
if not resolve_macos_cmake():
issues.append('Please install CMake from https://cmake.org')
return issues
def check_windows_host_tools() -> list[str]:
issues: list[str] = []
if not has_windows_build_tools():
issues.append('Please install Visual Studio with C++ Build Tools or Build Tools for Visual Studio')
if not shutil.which('cmake'):
issues.append('Please install CMake from https://cmake.org')
if not (shutil.which('py') or shutil.which('python')):
issues.append('Please install Python from https://www.python.org')
return issues
HOST_TOOL_CHECKERS: dict[str, Callable[[], list[str]]] = {
'linux': check_linux_host_tools,
'macos': check_macos_host_tools,
'windows': check_windows_host_tools,
}
def check_host_tools(host_name: str) -> list[str]:
host_checker = HOST_TOOL_CHECKERS.get(host_name)
if host_checker is None:
raise SystemExit(f'Unsupported host tools check: {host_name}')
return host_checker()
def build_flag_args(target_name: str, config: str | None = None) -> list[str]:
if target_name not in BUILD_TARGETS:
raise SystemExit(f'Unknown build target: {target_name}')
flags = {name: 0 for name in FLAG_NAMES}
flags.update(BUILD_TARGETS[target_name])
args = [f'-D{name}={value}' for name, value in flags.items()]
if config:
args.append(f'-DCMAKE_BUILD_TYPE={config}')
return args
def ensure_dir(path: str | Path) -> None:
Path(path).mkdir(parents=True, exist_ok=True)
def is_running_as_root() -> bool:
geteuid = getattr(os, 'geteuid', None)
return bool(geteuid and geteuid() == 0)
def remove_tree(path: str | Path) -> None:
def handle_remove_readonly(func: object, target: str, excinfo: object) -> None:
_ = func, excinfo
os.chmod(target, stat.S_IWRITE)
os.unlink(target)
shutil.rmtree(path, onexc=handle_remove_readonly)
def remove_path_if_exists(path: Path) -> None:
if path.is_dir() and not path.is_symlink():
remove_tree(path)
elif path.exists() or path.is_symlink():
path.unlink()
def ensure_empty_dir(path: Path) -> None:
remove_path_if_exists(path)
ensure_dir(path)
def copy_directory(source_path: str | Path, target_path: str | Path, dirs_exist_ok: bool = False) -> None:
shutil.copytree(source_path, target_path, dirs_exist_ok=dirs_exist_ok)
def download_file(url: str, target_path: Path, label: str) -> None:
log(f'Download {label}:', url)
urllib.request.urlretrieve(url, target_path)
def clone_git_repo(target_path: Path, repo_url: str, branch_name: str | None = None, depth: int | None = None) -> None:
command: list[object] = ['git', 'clone', repo_url]
if depth is not None:
command.extend(['--depth', str(depth)])
if branch_name is not None:
command.extend(['--branch', branch_name])
command.append(str(target_path))
run(command)
def resolve_runtime_build_script() -> str:
return 'build.cmd' if os.name == 'nt' else './build.sh'
def extract_zip_with_permissions(archive_path: Path, output_dir: Path) -> None:
with zipfile.ZipFile(archive_path) as archive:
for member in archive.infolist():
mode = member.external_attr >> 16
extracted_path = output_dir / member.filename
if member.is_dir():
extracted_path.mkdir(parents=True, exist_ok=True)
if mode:
extracted_path.chmod(mode)
continue
extracted_path.parent.mkdir(parents=True, exist_ok=True)
if stat.S_ISLNK(mode) and hasattr(os, 'symlink'):
if extracted_path.exists() or extracted_path.is_symlink():
extracted_path.unlink()
link_target = archive.read(member).decode('utf-8')
os.symlink(link_target, extracted_path)
continue
with archive.open(member) as source, extracted_path.open('wb') as destination:
shutil.copyfileobj(source, destination)
if mode:
extracted_path.chmod(mode)
def run(cmd: Sequence[object], cwd: str | Path | None = None, env: Mapping[str, str] | None = None) -> None:
log('Run:', ' '.join(str(part) for part in cmd))
subprocess.check_call([str(part) for part in cmd], cwd=cwd, env=dict(env) if env is not None else None)
def run_capture_text(
cmd: Sequence[object],
cwd: str | Path | None = None,
env: Mapping[str, str] | None = None,
*,
log_command: bool = True,
) -> str:
if log_command:
log('Run:', ' '.join(str(part) for part in cmd))
return subprocess.check_output(
[str(part) for part in cmd],
cwd=cwd,
env=dict(env) if env is not None else None,
text=True,
encoding='utf-8',
stderr=subprocess.STDOUT,
).strip()
def run_bash(command: str, cwd: str | Path | None = None, env: Mapping[str, str] | None = None) -> None:
log('Run:', command)
subprocess.check_call(['bash', '-lc', command], cwd=cwd, env=dict(env) if env is not None else None)
def resolve_windows_build(platform_name: str) -> tuple[str, str | None]:
build = WINDOWS_BUILD_BY_PLATFORM.get(platform_name)
if build is None:
raise SystemExit(f'Invalid Windows build platform: {platform_name}')
return build
def join_shell_args(args: Iterable[str]) -> str:
return ' '.join(shlex.quote(arg) for arg in args)
def join_windows_args(args: Iterable[str]) -> str:
return subprocess.list2cmdline([str(arg) for arg in args])
def discover_windows_ninja() -> str:
path = shutil.which('ninja')
if path:
return path
program_files_roots = [
Path(os.environ.get('ProgramFiles', r'C:\Program Files')),
Path(os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)')),
]
for root in program_files_roots:
for candidate in root.glob('Microsoft Visual Studio/*/*/Common7/IDE/CommonExtensions/Microsoft/CMake/Ninja/ninja.exe'):
if candidate.is_file():
return str(candidate)
raise SystemExit('ninja not found; install Ninja or Visual Studio CMake tools')
def run_in_emsdk_env(command: Sequence[str], workspace: Path, cwd: str | Path | None = None, env: Mapping[str, str] | None = None) -> None:
emscripten_root = workspace / 'emsdk'
if not emscripten_root.is_dir():
raise SystemExit(f'Workspace EMSDK is not prepared: {emscripten_root}')
if os.name == 'nt':
emscripten_env = emscripten_root / 'emsdk_env.bat'
if not emscripten_env.is_file():
raise SystemExit(f'Emscripten environment script not found: {emscripten_env}')
with tempfile.NamedTemporaryFile('w', suffix='.cmd', delete=False, encoding='utf-8') as script_file:
script_file.write('@echo off\n')
script_file.write(f'call "{emscripten_env}" >nul\n')
script_file.write('if errorlevel 1 exit /b %errorlevel%\n')
script_file.write(f'{join_windows_args(command)}\n')
temp_script = Path(script_file.name)
try:
run(['cmd', '/d', '/c', str(temp_script)], cwd=cwd, env=env)
finally:
temp_script.unlink(missing_ok=True)
else:
emscripten_env = emscripten_root / 'emsdk_env.sh'
if not emscripten_env.is_file():
raise SystemExit(f'Emscripten environment script not found: {emscripten_env}')
full_command = f'source "{emscripten_env}" >/dev/null && {join_shell_args(str(part) for part in command)}'
run_bash(full_command, cwd=cwd, env=env)
def build_toolset_version() -> str:
return f'v1-{os.name}'
def build_emscripten_version(env: Mapping[str, str]) -> str:
version = env.get('FO_EMSCRIPTEN_VERSION', '')
if not version:
raise SystemExit('FO_EMSCRIPTEN_VERSION is not configured')
return version
def build_android_ndk_version(env: Mapping[str, str]) -> str:
version = env.get('FO_ANDROID_NDK_VERSION', '')
if not version:
raise SystemExit('FO_ANDROID_NDK_VERSION is not configured')
return version
def build_android_sdk_version(env: Mapping[str, str]) -> str:
version = env.get('FO_ANDROID_SDK_VERSION', '')
if not version:
raise SystemExit('FO_ANDROID_SDK_VERSION is not configured')
return version
def build_android_sdk_archive_name(env: Mapping[str, str]) -> str:
version = build_android_sdk_version(env)
return f'commandlinetools-{resolve_android_sdk_host_tag()}-{version}_latest.zip'
def build_dotnet_version(env: Mapping[str, str]) -> str:
version = env.get('FO_DOTNET_RUNTIME', '')
if not version:
raise SystemExit('FO_DOTNET_RUNTIME is not configured')
return version
def build_xwin_version(env: Mapping[str, str]) -> str:
version = env.get('FO_XWIN_VERSION', '')
if not version:
raise SystemExit('FO_XWIN_VERSION is not configured (Engine/ThirdParty/xwin missing?)')
return version
def build_xwin_workspace_version(env: Mapping[str, str]) -> str:
return f'{build_xwin_version(env)}-{"-".join(XWIN_SPLAT_ARCHES)}'
def workspace_version_marker(workspace: Path, part_name: str) -> Path:
return workspace / f'{part_name}-version.txt'
def is_workspace_part_ready(workspace: Path, part_name: str, version: str) -> bool:
return read_first_line(workspace_version_marker(workspace, part_name)) == version
def mark_workspace_part_ready(workspace: Path, part_name: str, version: str) -> None:
workspace_version_marker(workspace, part_name).write_text(version + '\n', encoding='utf-8')
def ensure_workspace_part(
workspace: Path,
part_name: str,
version: str,
check_only: bool,
action: Callable[[Mapping[str, str]], None],
env: Mapping[str, str],
) -> None:
if is_workspace_part_ready(workspace, part_name, version):
log(f'Workspace part {part_name} is ready ({version})')
return
if check_only:
raise SystemExit(f'Workspace part {part_name} is not ready ({version})')
log(f'Prepare workspace part {part_name} ({version})')
action(env)
mark_workspace_part_ready(workspace, part_name, version)
def run_marker_step(marker_path: Path, action_name: str, action: Callable[[], None]) -> None:
if marker_path.exists():
return
log(action_name)
action()
marker_path.touch()
def reset_marker(marker_path: Path) -> None:
remove_path_if_exists(marker_path)
def ensure_directory_link(link_path: Path, target_path: str | Path) -> None:
if link_path.exists():
return
if os.name == 'nt':
run(['cmd', '/c', 'mklink', '/d', str(link_path), str(target_path)])
else:
link_path.symlink_to(Path(target_path), target_is_directory=True)
def upload_codecov(build_dir: Path, token: str) -> None:
codecov_path = build_dir / 'codecov'
reset_marker(codecov_path)
run(['curl', '-Os', 'https://uploader.codecov.io/latest/linux/codecov'], cwd=build_dir)
codecov_path.chmod(codecov_path.stat().st_mode | 0o111)
run([str(codecov_path), '-t', token, '--gcov'], cwd=build_dir)
def ensure_llvm_apt_source(workspace: Path, check_only: bool) -> None:
# Pin the LLVM apt.llvm.org repository to the same major as the project's
# minimum-required Clang (currently 20). Idempotent — llvm.sh detects an
# existing sources.list entry and reuses it.
marker_version = '20-1'
if is_workspace_part_ready(workspace, 'llvm-apt-source', marker_version):
return
if check_only:
raise SystemExit(f'Workspace part llvm-apt-source is not ready ({marker_version})')
ensure_dir(workspace)
llvm_sh = workspace / 'llvm-installer.sh'
if not llvm_sh.exists():
download_file('https://apt.llvm.org/llvm.sh', llvm_sh, 'LLVM installer')
llvm_sh.chmod(llvm_sh.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
sudo_prefix = [] if is_running_as_root() else ['sudo']
run([*sudo_prefix, 'bash', str(llvm_sh), '20'])
mark_workspace_part_ready(workspace, 'llvm-apt-source', marker_version)
def install_linux_packages(group_name: str, workspace: Path, check_only: bool) -> None:
version, packages = LINUX_PACKAGE_GROUPS[group_name]
if is_workspace_part_ready(workspace, group_name, version):
log(f'Workspace part {group_name} is ready ({version})')
return
if check_only:
raise SystemExit(f'Workspace part {group_name} is not ready ({version})')
if not shutil.which('apt-get'):
raise SystemExit('Please use a Debian/Ubuntu host with apt-get available')
if not is_running_as_root() and not shutil.which('sudo'):
raise SystemExit('Please install sudo or run the preparation script as root')
if any(_pkg_needs_llvm_apt_source(name) for name in packages):
ensure_llvm_apt_source(workspace, check_only)
package_manager = ['apt-get', '-qq', '-y', '-o', 'DPkg::Lock::Timeout=-1']
if not is_running_as_root():
package_manager.insert(0, 'sudo')
log(f'Install Linux package group {group_name}')
run([*package_manager, 'update'])
for package_name in packages:
log('Install', package_name)
run([*package_manager, 'install', package_name])
mark_workspace_part_ready(workspace, group_name, version)
_LLVM_VERSIONED_RE = re.compile(r'-(\d+)$')
def _pkg_needs_llvm_apt_source(package_name: str) -> bool:
# Any package ending in -<digits> coming from LLVM-versioned apt set
# (clang-20, llvm-20, lld-20, clang-tools-20, ...) needs apt.llvm.org.
match = _LLVM_VERSIONED_RE.search(package_name)
if not match:
return False
major = int(match.group(1))
return major >= 19 and package_name.split('-')[0] in {'clang', 'clang-format', 'clang-tools', 'clang-tidy', 'lld', 'lldb', 'llvm'}
def reset_build_dir(build_dir: Path) -> None:
if build_dir.exists():
remove_tree(build_dir)
ensure_dir(build_dir)
def make_output_path_cmake_args(output_path: str, binary_output_postfix: str = '') -> list[str]:
args = [f'-DFO_OUTPUT_PATH={to_cmake_path(output_path)}']
if binary_output_postfix:
args.append(f'-DFO_BINARY_OUTPUT_POSTFIX={binary_output_postfix}')
return args
def make_toolset_cmake_args(output_path: str, config_name: str | None = None, binary_output_postfix: str = '') -> list[str]:
return [*make_output_path_cmake_args(output_path, binary_output_postfix), *build_flag_args('toolset', config=config_name)]
def prepare_toolset_workspace(env: Mapping[str, str]) -> None:
output = env['FO_OUTPUT']
binary_output_postfix = env.get('FO_BINARY_OUTPUT_POSTFIX', '')
project_root = env['FO_PROJECT_ROOT']
build_dir = resolve_toolset_build_dir(env)
reset_build_dir(build_dir)
if os.name == 'nt':
run([
'cmake',
'-G',