| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import atexit |
| 4 |
import contextlib |
| 5 |
import glob |
| 6 |
import math |
| 7 |
import os |
| 8 |
import re |
| 9 |
import subprocess |
| 10 |
import sys |
| 11 |
import textwrap |
| 12 |
import zlib |
| 13 |
from collections import OrderedDict |
| 14 |
from io import StringIO |
| 15 |
from pathlib import Path |
| 16 |
from typing import Generator, TextIO, cast |
| 17 |
|
| 18 |
from misc.utility.color import print_error, print_info, print_warning |
| 19 |
from platform_methods import detect_arch |
| 20 |
|
| 21 |
|
| 22 |
base_folder = Path(__file__).resolve().parent |
| 23 |
|
| 24 |
compiler_version_cache = None |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
_scu_folders = set() |
| 29 |
|
| 30 |
|
| 31 |
def set_scu_folders(scu_folders): |
| 32 |
global _scu_folders |
| 33 |
_scu_folders = scu_folders |
| 34 |
|
| 35 |
|
| 36 |
def add_source_files_orig(self, sources, files, allow_gen=False): |
| 37 |
|
| 38 |
if isinstance(files, str): |
| 39 |
|
| 40 |
|
| 41 |
skip_gen_cpp = "*" in files |
| 42 |
files = self.Glob(files) |
| 43 |
if skip_gen_cpp and not allow_gen: |
| 44 |
files = [f for f in files if not str(f).endswith(".gen.cpp")] |
| 45 |
|
| 46 |
|
| 47 |
for file in files: |
| 48 |
obj = self.Object(file) |
| 49 |
if obj in sources: |
| 50 |
print_warning('Object "{}" already included in environment sources.'.format(obj)) |
| 51 |
continue |
| 52 |
sources.append(obj) |
| 53 |
|
| 54 |
|
| 55 |
def add_source_files_scu(self, sources, files, allow_gen=False): |
| 56 |
if self["scu_build"] and isinstance(files, str): |
| 57 |
if "*." not in files: |
| 58 |
return False |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
subdir = os.path.dirname(files) |
| 63 |
subdir = subdir if subdir == "" else subdir + "/" |
| 64 |
section_name = self.Dir(subdir).tpath |
| 65 |
section_name = section_name.replace("\\", "/") |
| 66 |
|
| 67 |
|
| 68 |
global _scu_folders |
| 69 |
if section_name not in (_scu_folders): |
| 70 |
return False |
| 71 |
|
| 72 |
|
| 73 |
add_source_files_orig(self, sources, subdir + ".scu/scu_*.gen.cpp", True) |
| 74 |
return True |
| 75 |
return False |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
def add_source_files(self, sources, files, allow_gen=False): |
| 81 |
if not add_source_files_scu(self, sources, files, allow_gen): |
| 82 |
|
| 83 |
add_source_files_orig(self, sources, files, allow_gen) |
| 84 |
return False |
| 85 |
return True |
| 86 |
|
| 87 |
|
| 88 |
def redirect_emitter(target, source, env): |
| 89 |
""" |
| 90 |
Emitter to automatically redirect object/library build files to the `bin/obj` directory, |
| 91 |
retaining subfolder structure. External build files will attempt to retain subfolder |
| 92 |
structure relative to their environment's parent directory, sorted under `bin/obj/external`. |
| 93 |
If `redirect_build_objects` is `False`, an external build file isn't relative to the passed |
| 94 |
environment, or a file is being written directly into `bin`, this emitter does nothing. |
| 95 |
""" |
| 96 |
if not env["redirect_build_objects"]: |
| 97 |
return target, source |
| 98 |
|
| 99 |
redirected_targets = [] |
| 100 |
for item in target: |
| 101 |
path = Path(item.get_abspath()).resolve() |
| 102 |
|
| 103 |
if path.parent == base_folder / "bin": |
| 104 |
pass |
| 105 |
elif base_folder in path.parents: |
| 106 |
item = env.File(f"#bin/obj/{path.relative_to(base_folder)}") |
| 107 |
elif (alt_base := Path(env.Dir(".").get_abspath()).resolve().parent) in path.parents: |
| 108 |
item = env.File(f"#bin/obj/external/{path.relative_to(alt_base)}") |
| 109 |
else: |
| 110 |
print_warning(f'Failed to redirect "{path}"') |
| 111 |
redirected_targets.append(item) |
| 112 |
return redirected_targets, source |
| 113 |
|
| 114 |
|
| 115 |
def disable_warnings(self): |
| 116 |
|
| 117 |
if self.msvc and not using_clang(self): |
| 118 |
self["WARNLEVEL"] = "/w" |
| 119 |
else: |
| 120 |
self["WARNLEVEL"] = "-w" |
| 121 |
|
| 122 |
|
| 123 |
def force_optimization_on_debug(self): |
| 124 |
|
| 125 |
if self["target"] == "template_release": |
| 126 |
return |
| 127 |
elif self.msvc: |
| 128 |
self["OPTIMIZELEVEL"] = "/O2" |
| 129 |
else: |
| 130 |
self["OPTIMIZELEVEL"] = "-O3" |
| 131 |
|
| 132 |
|
| 133 |
def add_module_version_string(self, s): |
| 134 |
self.module_version_string += "." + s |
| 135 |
|
| 136 |
|
| 137 |
def get_version_info(module_version_string="", silent=False): |
| 138 |
build_name = "custom_build" |
| 139 |
if os.getenv("BUILD_NAME") is not None: |
| 140 |
build_name = str(os.getenv("BUILD_NAME")) |
| 141 |
if not silent: |
| 142 |
print_info(f"Using custom build name: '{build_name}'.") |
| 143 |
|
| 144 |
import version |
| 145 |
|
| 146 |
version_info = { |
| 147 |
"short_name": str(version.short_name), |
| 148 |
"name": str(version.name), |
| 149 |
"major": int(version.major), |
| 150 |
"minor": int(version.minor), |
| 151 |
"patch": int(version.patch), |
| 152 |
"status": str(version.status), |
| 153 |
"build": str(build_name), |
| 154 |
"module_config": str(version.module_config) + module_version_string, |
| 155 |
"website": str(version.website), |
| 156 |
"docs_branch": str(version.docs), |
| 157 |
} |
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
if os.getenv("GODOT_VERSION_STATUS") is not None: |
| 162 |
version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS")) |
| 163 |
if not silent: |
| 164 |
print_info(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.") |
| 165 |
|
| 166 |
return version_info |
| 167 |
|
| 168 |
|
| 169 |
def get_git_info(): |
| 170 |
os.chdir(base_folder) |
| 171 |
|
| 172 |
|
| 173 |
git_hash = "" |
| 174 |
git_folder = ".git" |
| 175 |
|
| 176 |
if os.path.isfile(".git"): |
| 177 |
with open(".git", "r", encoding="utf-8") as file: |
| 178 |
module_folder = file.readline().strip() |
| 179 |
if module_folder.startswith("gitdir: "): |
| 180 |
git_folder = module_folder[8:] |
| 181 |
|
| 182 |
if os.path.isfile(os.path.join(git_folder, "HEAD")): |
| 183 |
with open(os.path.join(git_folder, "HEAD"), "r", encoding="utf8") as file: |
| 184 |
head = file.readline().strip() |
| 185 |
if head.startswith("ref: "): |
| 186 |
ref = head[5:] |
| 187 |
|
| 188 |
parts = git_folder.split("/") |
| 189 |
if len(parts) > 2 and parts[-2] == "worktrees": |
| 190 |
git_folder = "/".join(parts[0:-2]) |
| 191 |
head = os.path.join(git_folder, ref) |
| 192 |
packedrefs = os.path.join(git_folder, "packed-refs") |
| 193 |
if os.path.isfile(head): |
| 194 |
with open(head, "r", encoding="utf-8") as file: |
| 195 |
git_hash = file.readline().strip() |
| 196 |
elif os.path.isfile(packedrefs): |
| 197 |
|
| 198 |
|
| 199 |
for line in open(packedrefs, "r", encoding="utf-8").read().splitlines(): |
| 200 |
if line.startswith("#"): |
| 201 |
continue |
| 202 |
(line_hash, line_ref) = line.split(" ") |
| 203 |
if ref == line_ref: |
| 204 |
git_hash = line_hash |
| 205 |
break |
| 206 |
else: |
| 207 |
git_hash = head |
| 208 |
|
| 209 |
|
| 210 |
git_timestamp = 0 |
| 211 |
if os.path.exists(".git"): |
| 212 |
try: |
| 213 |
git_timestamp = subprocess.check_output( |
| 214 |
["git", "log", "-1", "--pretty=format:%ct", "--no-show-signature", git_hash], encoding="utf-8" |
| 215 |
) |
| 216 |
except (subprocess.CalledProcessError, OSError): |
| 217 |
|
| 218 |
pass |
| 219 |
|
| 220 |
return { |
| 221 |
"git_hash": git_hash, |
| 222 |
"git_timestamp": git_timestamp, |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
def get_cmdline_bool(option, default): |
| 227 |
"""We use `ARGUMENTS.get()` to check if options were manually overridden on the command line, |
| 228 |
and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings. |
| 229 |
""" |
| 230 |
from SCons.Script import ARGUMENTS |
| 231 |
from SCons.Variables.BoolVariable import _text2bool |
| 232 |
|
| 233 |
cmdline_val = ARGUMENTS.get(option) |
| 234 |
if cmdline_val is not None: |
| 235 |
return _text2bool(cmdline_val) |
| 236 |
else: |
| 237 |
return default |
| 238 |
|
| 239 |
|
| 240 |
def detect_modules(search_path, recursive=False): |
| 241 |
"""Detects and collects a list of C++ modules at specified path |
| 242 |
|
| 243 |
`search_path` - a directory path containing modules. The path may point to |
| 244 |
a single module, which may have other nested modules. A module must have |
| 245 |
"register_types.h", "SCsub", "config.py" files created to be detected. |
| 246 |
|
| 247 |
`recursive` - if `True`, then all subdirectories are searched for modules as |
| 248 |
specified by the `search_path`, otherwise collects all modules under the |
| 249 |
`search_path` directory. If the `search_path` is a module, it is collected |
| 250 |
in all cases. |
| 251 |
|
| 252 |
Returns an `OrderedDict` with module names as keys, and directory paths as |
| 253 |
values. If a path is relative, then it is a built-in module. If a path is |
| 254 |
absolute, then it is a custom module collected outside of the engine source. |
| 255 |
""" |
| 256 |
modules = OrderedDict() |
| 257 |
|
| 258 |
def add_module(path): |
| 259 |
module_name = os.path.basename(path) |
| 260 |
module_path = path.replace("\\", "/") |
| 261 |
modules[module_name] = module_path |
| 262 |
|
| 263 |
def is_engine(path): |
| 264 |
|
| 265 |
|
| 266 |
version_path = os.path.join(path, "version.py") |
| 267 |
if os.path.exists(version_path): |
| 268 |
with open(version_path, "r", encoding="utf-8") as f: |
| 269 |
if 'short_name = "godot"' in f.read(): |
| 270 |
return True |
| 271 |
return False |
| 272 |
|
| 273 |
def get_files(path): |
| 274 |
files = glob.glob(os.path.join(path, "*")) |
| 275 |
|
| 276 |
|
| 277 |
files.sort() |
| 278 |
return files |
| 279 |
|
| 280 |
if not recursive: |
| 281 |
if is_module(search_path): |
| 282 |
add_module(search_path) |
| 283 |
for path in get_files(search_path): |
| 284 |
if is_engine(path): |
| 285 |
continue |
| 286 |
if is_module(path): |
| 287 |
add_module(path) |
| 288 |
else: |
| 289 |
to_search = [search_path] |
| 290 |
while to_search: |
| 291 |
path = to_search.pop() |
| 292 |
if is_module(path): |
| 293 |
add_module(path) |
| 294 |
for child in get_files(path): |
| 295 |
if not os.path.isdir(child): |
| 296 |
continue |
| 297 |
if is_engine(child): |
| 298 |
continue |
| 299 |
to_search.insert(0, child) |
| 300 |
return modules |
| 301 |
|
| 302 |
|
| 303 |
def is_module(path): |
| 304 |
if not os.path.isdir(path): |
| 305 |
return False |
| 306 |
must_exist = ["register_types.h", "SCsub", "config.py"] |
| 307 |
for f in must_exist: |
| 308 |
if not os.path.exists(os.path.join(path, f)): |
| 309 |
return False |
| 310 |
return True |
| 311 |
|
| 312 |
|
| 313 |
def convert_custom_modules_path(path): |
| 314 |
if not path: |
| 315 |
return path |
| 316 |
path = os.path.realpath(os.path.expanduser(os.path.expandvars(path))) |
| 317 |
err_msg = "Build option 'custom_modules' must %s" |
| 318 |
if not os.path.isdir(path): |
| 319 |
raise ValueError(err_msg % "point to an existing directory.") |
| 320 |
if path == os.path.realpath("modules"): |
| 321 |
raise ValueError(err_msg % "be a directory other than built-in `modules` directory.") |
| 322 |
return path |
| 323 |
|
| 324 |
|
| 325 |
def module_add_dependencies(self, module, dependencies, optional=False): |
| 326 |
""" |
| 327 |
Adds dependencies for a given module. |
| 328 |
Meant to be used in module `can_build` methods. |
| 329 |
""" |
| 330 |
if module not in self.module_dependencies: |
| 331 |
self.module_dependencies[module] = [[], []] |
| 332 |
if optional: |
| 333 |
self.module_dependencies[module][1].extend(dependencies) |
| 334 |
else: |
| 335 |
self.module_dependencies[module][0].extend(dependencies) |
| 336 |
|
| 337 |
|
| 338 |
def module_check_dependencies(self, module): |
| 339 |
""" |
| 340 |
Checks if module dependencies are enabled for a given module, |
| 341 |
and prints a warning if they aren't. |
| 342 |
Meant to be used in module `can_build` methods. |
| 343 |
Returns a boolean (True if dependencies are satisfied). |
| 344 |
""" |
| 345 |
missing_deps = set() |
| 346 |
required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else [] |
| 347 |
for dep in required_deps: |
| 348 |
opt = "module_{}_enabled".format(dep) |
| 349 |
if opt not in self or not self[opt] or not module_check_dependencies(self, dep): |
| 350 |
missing_deps.add(dep) |
| 351 |
|
| 352 |
if missing_deps: |
| 353 |
if module not in self.disabled_modules: |
| 354 |
print_warning( |
| 355 |
"Disabling '{}' module as the following dependencies are not satisfied: {}".format( |
| 356 |
module, ", ".join(missing_deps) |
| 357 |
) |
| 358 |
) |
| 359 |
self.disabled_modules.add(module) |
| 360 |
return False |
| 361 |
else: |
| 362 |
return True |
| 363 |
|
| 364 |
|
| 365 |
def sort_module_list(env): |
| 366 |
deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()} |
| 367 |
|
| 368 |
frontier = list(env.module_list.keys()) |
| 369 |
explored = [] |
| 370 |
while len(frontier): |
| 371 |
cur = frontier.pop() |
| 372 |
deps_list = deps[cur] if cur in deps else [] |
| 373 |
if len(deps_list) and any([d not in explored for d in deps_list]): |
| 374 |
|
| 375 |
frontier.insert(0, cur) |
| 376 |
continue |
| 377 |
explored.append(cur) |
| 378 |
for k in explored: |
| 379 |
env.module_list.move_to_end(k) |
| 380 |
|
| 381 |
|
| 382 |
def use_windows_spawn_fix(self, platform=None): |
| 383 |
if os.name != "nt": |
| 384 |
return |
| 385 |
|
| 386 |
def mySubProcess(cmdline, env): |
| 387 |
startupinfo = subprocess.STARTUPINFO() |
| 388 |
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW |
| 389 |
popen_args = { |
| 390 |
"stdin": subprocess.PIPE, |
| 391 |
"stdout": subprocess.PIPE, |
| 392 |
"stderr": subprocess.PIPE, |
| 393 |
"startupinfo": startupinfo, |
| 394 |
"shell": False, |
| 395 |
"env": env, |
| 396 |
} |
| 397 |
popen_args["text"] = True |
| 398 |
proc = subprocess.Popen(cmdline, **popen_args) |
| 399 |
_, err = proc.communicate() |
| 400 |
rv = proc.wait() |
| 401 |
if rv: |
| 402 |
print_error(err) |
| 403 |
elif len(err) > 0 and not err.isspace(): |
| 404 |
print(err) |
| 405 |
return rv |
| 406 |
|
| 407 |
def mySpawn(sh, escape, cmd, args, env): |
| 408 |
|
| 409 |
if cmd == "del": |
| 410 |
os.remove(args[1]) |
| 411 |
return 0 |
| 412 |
|
| 413 |
newargs = " ".join(args[1:]) |
| 414 |
cmdline = cmd + " " + newargs |
| 415 |
|
| 416 |
rv = 0 |
| 417 |
env = {str(key): str(value) for key, value in iter(env.items())} |
| 418 |
rv = mySubProcess(cmdline, env) |
| 419 |
|
| 420 |
return rv |
| 421 |
|
| 422 |
self["SPAWN"] = mySpawn |
| 423 |
|
| 424 |
|
| 425 |
def no_verbose(env): |
| 426 |
from misc.utility.color import Ansi, is_stdout_color |
| 427 |
|
| 428 |
colors = [Ansi.BLUE, Ansi.BOLD, Ansi.REGULAR, Ansi.RESET] if is_stdout_color() else ["", "", "", ""] |
| 429 |
|
| 430 |
|
| 431 |
|
| 432 |
compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors) |
| 433 |
java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors) |
| 434 |
compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors) |
| 435 |
link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors) |
| 436 |
link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors) |
| 437 |
ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors) |
| 438 |
link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors) |
| 439 |
java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors) |
| 440 |
compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors) |
| 441 |
zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors) |
| 442 |
generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors) |
| 443 |
|
| 444 |
env["CXXCOMSTR"] = compile_source_message |
| 445 |
env["CCCOMSTR"] = compile_source_message |
| 446 |
env["SWIFTCOMSTR"] = compile_source_message |
| 447 |
env["SHCCCOMSTR"] = compile_shared_source_message |
| 448 |
env["SHCXXCOMSTR"] = compile_shared_source_message |
| 449 |
env["ARCOMSTR"] = link_library_message |
| 450 |
env["RANLIBCOMSTR"] = ranlib_library_message |
| 451 |
env["SHLINKCOMSTR"] = link_shared_library_message |
| 452 |
env["LINKCOMSTR"] = link_program_message |
| 453 |
env["JARCOMSTR"] = java_library_message |
| 454 |
env["JAVACCOMSTR"] = java_compile_source_message |
| 455 |
env["RCCOMSTR"] = compiled_resource_message |
| 456 |
env["ZIPCOMSTR"] = zip_archive_message |
| 457 |
env["GENCOMSTR"] = generated_file_message |
| 458 |
|
| 459 |
|
| 460 |
def detect_visual_c_compiler_version(tools_env): |
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
vc_chosen_compiler_index = -1 |
| 484 |
vc_chosen_compiler_str = "" |
| 485 |
|
| 486 |
|
| 487 |
if "VCTOOLSINSTALLDIR" in tools_env: |
| 488 |
|
| 489 |
vc_amd64_compiler_detection_index = ( |
| 490 |
tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;") |
| 491 |
) |
| 492 |
if vc_amd64_compiler_detection_index > -1: |
| 493 |
vc_chosen_compiler_index = vc_amd64_compiler_detection_index |
| 494 |
vc_chosen_compiler_str = "amd64" |
| 495 |
|
| 496 |
vc_amd64_x86_compiler_detection_index = ( |
| 497 |
tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;") |
| 498 |
) |
| 499 |
if vc_amd64_x86_compiler_detection_index > -1 and ( |
| 500 |
vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index |
| 501 |
): |
| 502 |
vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index |
| 503 |
vc_chosen_compiler_str = "amd64_x86" |
| 504 |
|
| 505 |
vc_x86_compiler_detection_index = ( |
| 506 |
tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;") |
| 507 |
) |
| 508 |
if vc_x86_compiler_detection_index > -1 and ( |
| 509 |
vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index |
| 510 |
): |
| 511 |
vc_chosen_compiler_index = vc_x86_compiler_detection_index |
| 512 |
vc_chosen_compiler_str = "x86" |
| 513 |
|
| 514 |
vc_x86_amd64_compiler_detection_index = ( |
| 515 |
tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;") |
| 516 |
) |
| 517 |
if vc_x86_amd64_compiler_detection_index > -1 and ( |
| 518 |
vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index |
| 519 |
): |
| 520 |
vc_chosen_compiler_str = "x86_amd64" |
| 521 |
|
| 522 |
return vc_chosen_compiler_str |
| 523 |
|
| 524 |
|
| 525 |
def find_visual_c_batch_file(env): |
| 526 |
|
| 527 |
from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target |
| 528 |
|
| 529 |
msvc_version = get_default_version(env) |
| 530 |
|
| 531 |
|
| 532 |
if env.scons_version >= (4, 4, 0): |
| 533 |
(host_platform, target_platform, _) = get_host_target(env, msvc_version) |
| 534 |
else: |
| 535 |
(host_platform, target_platform, _) = get_host_target(env) |
| 536 |
|
| 537 |
if env.scons_version < (4, 6, 0): |
| 538 |
return find_batch_file(env, msvc_version, host_platform, target_platform)[0] |
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
product_dir = find_vc_pdir(msvc_version=msvc_version, env=env) |
| 544 |
|
| 545 |
return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0] |
| 546 |
|
| 547 |
|
| 548 |
def generate_cpp_hint_file(filename): |
| 549 |
if os.path.isfile(filename): |
| 550 |
|
| 551 |
pass |
| 552 |
else: |
| 553 |
try: |
| 554 |
with open(filename, "w", encoding="utf-8", newline="\n") as fd: |
| 555 |
fd.write("#define GDCLASS(m_class, m_inherits)\n") |
| 556 |
for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]: |
| 557 |
for count in range(13): |
| 558 |
for suffix in ["", "R", "C", "RC"]: |
| 559 |
fd.write(f"#define {name}{count}{suffix}(") |
| 560 |
if "R" in suffix: |
| 561 |
fd.write("m_ret, ") |
| 562 |
fd.write("m_name") |
| 563 |
for idx in range(1, count + 1): |
| 564 |
fd.write(f", type{idx}") |
| 565 |
fd.write(")\n") |
| 566 |
|
| 567 |
except OSError: |
| 568 |
print_warning("Could not write cpp.hint file.") |
| 569 |
|
| 570 |
|
| 571 |
def glob_recursive(pattern, node="."): |
| 572 |
from SCons import Node |
| 573 |
from SCons.Script import Glob |
| 574 |
|
| 575 |
results = [] |
| 576 |
for f in Glob(str(node) + "/*", source=True): |
| 577 |
if type(f) is Node.FS.Dir: |
| 578 |
results += glob_recursive(pattern, f) |
| 579 |
results += Glob(str(node) + "/" + pattern, source=True) |
| 580 |
return results |
| 581 |
|
| 582 |
|
| 583 |
def precious_program(env, program, sources, **args): |
| 584 |
program = env.Program(program, sources, **args) |
| 585 |
env.Precious(program) |
| 586 |
return program |
| 587 |
|
| 588 |
|
| 589 |
def add_shared_library(env, name, sources, **args): |
| 590 |
library = env.SharedLibrary(name, sources, **args) |
| 591 |
env.NoCache(library) |
| 592 |
return library |
| 593 |
|
| 594 |
|
| 595 |
def add_library(env, name, sources, **args): |
| 596 |
library = env.Library(name, sources, **args) |
| 597 |
env.NoCache(library) |
| 598 |
return library |
| 599 |
|
| 600 |
|
| 601 |
def add_program(env, name, sources, **args): |
| 602 |
program = env.Program(name, sources, **args) |
| 603 |
env.NoCache(program) |
| 604 |
return program |
| 605 |
|
| 606 |
|
| 607 |
def CommandNoCache(env, target, sources, command, **args): |
| 608 |
result = env.Command(target, sources, command, **args) |
| 609 |
env.NoCache(result) |
| 610 |
return result |
| 611 |
|
| 612 |
|
| 613 |
def Run(env, function, comstr="$GENCOMSTR"): |
| 614 |
from SCons.Script import Action |
| 615 |
|
| 616 |
return Action(function, comstr) |
| 617 |
|
| 618 |
|
| 619 |
def detect_darwin_toolchain_path(env): |
| 620 |
var_name = "APPLE_TOOLCHAIN_PATH" |
| 621 |
if not env[var_name]: |
| 622 |
try: |
| 623 |
xcode_path = subprocess.check_output(["xcode-select", "-p"]).strip().decode("utf-8") |
| 624 |
if xcode_path: |
| 625 |
env[var_name] = xcode_path + "/Toolchains/XcodeDefault.xctoolchain" |
| 626 |
except (subprocess.CalledProcessError, OSError): |
| 627 |
print_error("Failed to find SDK path while running 'xcode-select -p'.") |
| 628 |
raise |
| 629 |
|
| 630 |
|
| 631 |
def detect_darwin_sdk_path(platform, env): |
| 632 |
sdk_name = "" |
| 633 |
|
| 634 |
if platform == "macos": |
| 635 |
sdk_name = "macosx" |
| 636 |
var_name = "MACOS_SDK_PATH" |
| 637 |
|
| 638 |
elif platform == "ios": |
| 639 |
sdk_name = "iphoneos" |
| 640 |
var_name = "APPLE_SDK_PATH" |
| 641 |
|
| 642 |
elif platform == "iossimulator": |
| 643 |
sdk_name = "iphonesimulator" |
| 644 |
var_name = "APPLE_SDK_PATH" |
| 645 |
|
| 646 |
elif platform == "visionos": |
| 647 |
sdk_name = "xros" |
| 648 |
var_name = "APPLE_SDK_PATH" |
| 649 |
|
| 650 |
elif platform == "visionossimulator": |
| 651 |
sdk_name = "xrsimulator" |
| 652 |
var_name = "APPLE_SDK_PATH" |
| 653 |
|
| 654 |
else: |
| 655 |
raise Exception("Invalid platform argument passed to detect_darwin_sdk_path") |
| 656 |
|
| 657 |
if not env[var_name]: |
| 658 |
try: |
| 659 |
sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8") |
| 660 |
if sdk_path: |
| 661 |
env[var_name] = sdk_path |
| 662 |
except (subprocess.CalledProcessError, OSError): |
| 663 |
print_error("Failed to find SDK path while running 'xcrun --sdk {} --show-sdk-path'.".format(sdk_name)) |
| 664 |
raise |
| 665 |
|
| 666 |
|
| 667 |
def is_apple_clang(env): |
| 668 |
import shlex |
| 669 |
|
| 670 |
if env["platform"] not in ["macos", "ios"]: |
| 671 |
return False |
| 672 |
if not using_clang(env): |
| 673 |
return False |
| 674 |
try: |
| 675 |
version = ( |
| 676 |
subprocess.check_output(shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"]) |
| 677 |
.strip() |
| 678 |
.decode("utf-8") |
| 679 |
) |
| 680 |
except (subprocess.CalledProcessError, OSError): |
| 681 |
print_warning("Couldn't parse CXX environment variable to infer compiler version.") |
| 682 |
return False |
| 683 |
return version.startswith("Apple") |
| 684 |
|
| 685 |
|
| 686 |
def get_compiler_version(env): |
| 687 |
""" |
| 688 |
Returns a dictionary with various version information: |
| 689 |
|
| 690 |
- major, minor, patch: Version following semantic versioning system |
| 691 |
- metadata1, metadata2: Extra information |
| 692 |
- date: Date of the build |
| 693 |
""" |
| 694 |
|
| 695 |
global compiler_version_cache |
| 696 |
if compiler_version_cache is not None: |
| 697 |
return compiler_version_cache |
| 698 |
|
| 699 |
import shlex |
| 700 |
|
| 701 |
ret = { |
| 702 |
"major": -1, |
| 703 |
"minor": -1, |
| 704 |
"patch": -1, |
| 705 |
"metadata1": "", |
| 706 |
"metadata2": "", |
| 707 |
"date": "", |
| 708 |
"apple_major": -1, |
| 709 |
"apple_minor": -1, |
| 710 |
"apple_patch1": -1, |
| 711 |
"apple_patch2": -1, |
| 712 |
"apple_patch3": -1, |
| 713 |
} |
| 714 |
|
| 715 |
if env.msvc and not using_clang(env): |
| 716 |
try: |
| 717 |
|
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
args = [ |
| 722 |
env["VSWHERE"], |
| 723 |
"-latest", |
| 724 |
"-prerelease", |
| 725 |
"-products", |
| 726 |
"*", |
| 727 |
"-requires", |
| 728 |
"Microsoft.Component.MSBuild", |
| 729 |
"-utf8", |
| 730 |
] |
| 731 |
version = subprocess.check_output(args, encoding="utf-8").strip() |
| 732 |
for line in version.splitlines(): |
| 733 |
split = line.split(":", 1) |
| 734 |
if split[0] == "catalog_productSemanticVersion": |
| 735 |
match = re.match(r" ([0-9]*).([0-9]*).([0-9]*)-?([a-z0-9.+]*)", split[1]) |
| 736 |
if match is not None: |
| 737 |
ret["major"] = int(match.group(1)) |
| 738 |
ret["minor"] = int(match.group(2)) |
| 739 |
ret["patch"] = int(match.group(3)) |
| 740 |
|
| 741 |
ret["metadata2"] = match.group(4) |
| 742 |
|
| 743 |
|
| 744 |
if split[0] == "catalog_buildVersion": |
| 745 |
ret["metadata1"] = split[1] |
| 746 |
except (subprocess.CalledProcessError, OSError): |
| 747 |
print_warning("Couldn't find vswhere to determine compiler version.") |
| 748 |
return update_compiler_version_cache(ret) |
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
try: |
| 753 |
version = subprocess.check_output( |
| 754 |
shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"], shell=(os.name == "nt"), encoding="utf-8" |
| 755 |
).strip() |
| 756 |
except (subprocess.CalledProcessError, OSError): |
| 757 |
print_warning("Couldn't parse CXX environment variable to infer compiler version.") |
| 758 |
return update_compiler_version_cache(ret) |
| 759 |
|
| 760 |
match = re.search( |
| 761 |
r"(?:(?<=version )|(?<=\) )|(?<=^))" |
| 762 |
r"(?P<major>\d+)" |
| 763 |
r"(?:\.(?P<minor>\d*))?" |
| 764 |
r"(?:\.(?P<patch>\d*))?" |
| 765 |
r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?" |
| 766 |
r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?" |
| 767 |
r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?", |
| 768 |
version, |
| 769 |
) |
| 770 |
if match is not None: |
| 771 |
for key, value in match.groupdict().items(): |
| 772 |
if value is not None: |
| 773 |
ret[key] = value |
| 774 |
|
| 775 |
match_apple = re.search( |
| 776 |
r"(?:(?<=clang-)|(?<=\) )|(?<=^))" |
| 777 |
r"(?P<apple_major>\d+)" |
| 778 |
r"(?:\.(?P<apple_minor>\d*))?" |
| 779 |
r"(?:\.(?P<apple_patch1>\d*))?" |
| 780 |
r"(?:\.(?P<apple_patch2>\d*))?" |
| 781 |
r"(?:\.(?P<apple_patch3>\d*))?", |
| 782 |
version, |
| 783 |
) |
| 784 |
if match_apple is not None: |
| 785 |
for key, value in match_apple.groupdict().items(): |
| 786 |
if value is not None: |
| 787 |
ret[key] = value |
| 788 |
|
| 789 |
|
| 790 |
for key in [ |
| 791 |
"major", |
| 792 |
"minor", |
| 793 |
"patch", |
| 794 |
"apple_major", |
| 795 |
"apple_minor", |
| 796 |
"apple_patch1", |
| 797 |
"apple_patch2", |
| 798 |
"apple_patch3", |
| 799 |
]: |
| 800 |
ret[key] = int(ret[key] or -1) |
| 801 |
return update_compiler_version_cache(ret) |
| 802 |
|
| 803 |
|
| 804 |
def update_compiler_version_cache(value): |
| 805 |
global compiler_version_cache |
| 806 |
compiler_version_cache = value |
| 807 |
return value |
| 808 |
|
| 809 |
|
| 810 |
def using_gcc(env): |
| 811 |
return "gcc" in os.path.basename(env["CC"]) |
| 812 |
|
| 813 |
|
| 814 |
def using_clang(env): |
| 815 |
return "clang" in os.path.basename(env["CC"]) |
| 816 |
|
| 817 |
|
| 818 |
def using_emcc(env): |
| 819 |
return "emcc" in os.path.basename(env["CC"]) |
| 820 |
|
| 821 |
|
| 822 |
def show_progress(env): |
| 823 |
|
| 824 |
if env["ninja"]: |
| 825 |
return |
| 826 |
|
| 827 |
NODE_COUNT_FILENAME = base_folder / ".scons_node_count" |
| 828 |
|
| 829 |
class ShowProgress: |
| 830 |
def __init__(self): |
| 831 |
self.count = 0 |
| 832 |
self.max = 0 |
| 833 |
try: |
| 834 |
with open(NODE_COUNT_FILENAME, "r", encoding="utf-8") as f: |
| 835 |
self.max = int(f.readline()) |
| 836 |
except OSError: |
| 837 |
pass |
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
self.display = cast(bool, env["progress"] and sys.stdout.isatty()) |
| 842 |
if self.display and not self.max: |
| 843 |
print_info("Performing initial build, progress percentage unavailable!") |
| 844 |
self.display = False |
| 845 |
|
| 846 |
def __call__(self, node, *args, **kw): |
| 847 |
self.count += 1 |
| 848 |
if self.display: |
| 849 |
percent = int(min(self.count * 100 / self.max, 100)) |
| 850 |
sys.stdout.write(f"\r[{percent:3d}%] ") |
| 851 |
sys.stdout.flush() |
| 852 |
|
| 853 |
from SCons.Script import Progress |
| 854 |
from SCons.Script.Main import GetBuildFailures |
| 855 |
|
| 856 |
progressor = ShowProgress() |
| 857 |
Progress(progressor) |
| 858 |
|
| 859 |
def progress_finish(): |
| 860 |
if GetBuildFailures() or not progressor.count: |
| 861 |
return |
| 862 |
try: |
| 863 |
with open(NODE_COUNT_FILENAME, "w", encoding="utf-8", newline="\n") as f: |
| 864 |
f.write(f"{progressor.count}\n") |
| 865 |
except OSError: |
| 866 |
pass |
| 867 |
|
| 868 |
atexit.register(progress_finish) |
| 869 |
|
| 870 |
|
| 871 |
def convert_size(size_bytes: int) -> str: |
| 872 |
if size_bytes == 0: |
| 873 |
return "0 bytes" |
| 874 |
SIZE_NAMES = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] |
| 875 |
index = math.floor(math.log(size_bytes, 1024)) |
| 876 |
power = math.pow(1024, index) |
| 877 |
size = round(size_bytes / power, 2) |
| 878 |
return f"{size} {SIZE_NAMES[index]}" |
| 879 |
|
| 880 |
|
| 881 |
def get_size(start_path: str = ".") -> int: |
| 882 |
total_size = 0 |
| 883 |
for dirpath, _, filenames in os.walk(start_path): |
| 884 |
for file in filenames: |
| 885 |
path = os.path.join(dirpath, file) |
| 886 |
total_size += os.path.getsize(path) |
| 887 |
return total_size |
| 888 |
|
| 889 |
|
| 890 |
def clean_cache(cache_path: str, cache_limit: int, verbose: bool) -> None: |
| 891 |
if not cache_limit: |
| 892 |
return |
| 893 |
|
| 894 |
files = glob.glob(os.path.join(cache_path, "*", "*")) |
| 895 |
if not files: |
| 896 |
return |
| 897 |
|
| 898 |
|
| 899 |
stats = [] |
| 900 |
for file in files: |
| 901 |
try: |
| 902 |
stats.append((file, *os.stat(file)[6:8])) |
| 903 |
except OSError: |
| 904 |
print_error(f'Failed to access cache file "{file}"; skipping.') |
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
stats.sort(key=lambda x: x[2], reverse=True) |
| 909 |
sum = 0 |
| 910 |
for index, stat in enumerate(stats): |
| 911 |
sum += stat[1] |
| 912 |
if sum > cache_limit: |
| 913 |
purge = [x[0] for x in stats[index:]] |
| 914 |
count = len(purge) |
| 915 |
for file in purge: |
| 916 |
try: |
| 917 |
os.remove(file) |
| 918 |
except OSError: |
| 919 |
print_error(f'Failed to remove cache file "{file}"; skipping.') |
| 920 |
count -= 1 |
| 921 |
if verbose and count: |
| 922 |
print_info(f"Purged {count} file{'s' if count else ''} from cache.") |
| 923 |
break |
| 924 |
|
| 925 |
|
| 926 |
def prepare_cache(env) -> None: |
| 927 |
cache_path = "" |
| 928 |
if env["cache_path"]: |
| 929 |
cache_path = cast(str, env["cache_path"]) |
| 930 |
elif os.environ.get("SCONS_CACHE"): |
| 931 |
print_warning("Environment variable `SCONS_CACHE` is deprecated; use `cache_path` argument instead.") |
| 932 |
cache_path = cast(str, os.environ.get("SCONS_CACHE")) |
| 933 |
|
| 934 |
if not cache_path: |
| 935 |
return |
| 936 |
|
| 937 |
env.CacheDir(cache_path) |
| 938 |
print(f'SCons cache enabled... (path: "{cache_path}")') |
| 939 |
|
| 940 |
if env["cache_limit"]: |
| 941 |
cache_limit = float(env["cache_limit"]) |
| 942 |
elif os.environ.get("SCONS_CACHE_LIMIT"): |
| 943 |
print_warning("Environment variable `SCONS_CACHE_LIMIT` is deprecated; use `cache_limit` argument instead.") |
| 944 |
cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", "0")) / 1024 |
| 945 |
|
| 946 |
|
| 947 |
cache_limit = max(0, int(cache_limit * 1024 * 1024 * 1024)) |
| 948 |
if env["verbose"]: |
| 949 |
print_info( |
| 950 |
f"Current cache size is {convert_size(get_size(cache_path))}" |
| 951 |
+ (f" (limit: {convert_size(cache_limit)})" if cache_limit else "") |
| 952 |
) |
| 953 |
|
| 954 |
atexit.register(clean_cache, cache_path, cache_limit, env["verbose"]) |
| 955 |
|
| 956 |
|
| 957 |
def prepare_purge(env): |
| 958 |
from SCons.Script.Main import GetBuildFailures |
| 959 |
|
| 960 |
def purge_flaky_files(): |
| 961 |
paths_to_keep = [env["ninja_file"]] |
| 962 |
for build_failure in GetBuildFailures(): |
| 963 |
path = build_failure.node.path |
| 964 |
if os.path.isfile(path) and path not in paths_to_keep: |
| 965 |
os.remove(path) |
| 966 |
|
| 967 |
atexit.register(purge_flaky_files) |
| 968 |
|
| 969 |
|
| 970 |
def prepare_timer(): |
| 971 |
import time |
| 972 |
|
| 973 |
def print_elapsed_time(time_at_start: float): |
| 974 |
time_elapsed = time.time() - time_at_start |
| 975 |
time_formatted = time.strftime("%H:%M:%S", time.gmtime(time_elapsed)) |
| 976 |
time_centiseconds = (time_elapsed % 1) * 100 |
| 977 |
print_info(f"Time elapsed: {time_formatted}.{time_centiseconds:02.0f}") |
| 978 |
|
| 979 |
atexit.register(print_elapsed_time, time.time()) |
| 980 |
|
| 981 |
|
| 982 |
def dump(env): |
| 983 |
""" |
| 984 |
Dumps latest build information for debugging purposes and external tools. |
| 985 |
""" |
| 986 |
|
| 987 |
with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as file: |
| 988 |
file.write(env.Dump(format="json")) |
| 989 |
|
| 990 |
|
| 991 |
|
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
|
| 1009 |
|
| 1010 |
def generate_vs_project(env, original_args, project_name="godot"): |
| 1011 |
|
| 1012 |
def glob_recursive_2(pattern, dirs, node="."): |
| 1013 |
from SCons import Node |
| 1014 |
from SCons.Script import Glob |
| 1015 |
|
| 1016 |
results = [] |
| 1017 |
for f in Glob(str(node) + "/*", source=True): |
| 1018 |
if type(f) is Node.FS.Dir: |
| 1019 |
results += glob_recursive_2(pattern, dirs, f) |
| 1020 |
r = Glob(str(node) + "/" + pattern, source=True) |
| 1021 |
if len(r) > 0 and str(node) not in dirs: |
| 1022 |
d = "" |
| 1023 |
for part in str(node).split("\\"): |
| 1024 |
d += part |
| 1025 |
if d not in dirs: |
| 1026 |
dirs.append(d) |
| 1027 |
d += "\\" |
| 1028 |
results += r |
| 1029 |
return results |
| 1030 |
|
| 1031 |
def get_bool(args, option, default): |
| 1032 |
from SCons.Variables.BoolVariable import _text2bool |
| 1033 |
|
| 1034 |
val = args.get(option, default) |
| 1035 |
if val is not None: |
| 1036 |
try: |
| 1037 |
return _text2bool(val) |
| 1038 |
except (ValueError, AttributeError): |
| 1039 |
return default |
| 1040 |
else: |
| 1041 |
return default |
| 1042 |
|
| 1043 |
def format_key_value(v): |
| 1044 |
if type(v) in [tuple, list]: |
| 1045 |
return v[0] if len(v) == 1 else f"{v[0]}={v[1]}" |
| 1046 |
return v |
| 1047 |
|
| 1048 |
def get_dependencies(file, env, exts, headers, sources, others): |
| 1049 |
for child in file.children(): |
| 1050 |
if isinstance(child, str): |
| 1051 |
child = env.File(x) |
| 1052 |
fname = "" |
| 1053 |
try: |
| 1054 |
fname = child.path |
| 1055 |
except AttributeError: |
| 1056 |
|
| 1057 |
pass |
| 1058 |
|
| 1059 |
if fname: |
| 1060 |
parts = os.path.splitext(fname) |
| 1061 |
if len(parts) > 1: |
| 1062 |
ext = parts[1].lower() |
| 1063 |
if ext in exts["sources"]: |
| 1064 |
sources += [fname] |
| 1065 |
elif ext in exts["headers"]: |
| 1066 |
headers += [fname] |
| 1067 |
elif ext in exts["others"]: |
| 1068 |
others += [fname] |
| 1069 |
|
| 1070 |
get_dependencies(child, env, exts, headers, sources, others) |
| 1071 |
|
| 1072 |
filtered_args = original_args.copy() |
| 1073 |
|
| 1074 |
|
| 1075 |
filtered_args.pop("vsproj", None) |
| 1076 |
|
| 1077 |
|
| 1078 |
|
| 1079 |
filtered_args.pop("vsproj_gen_only", None) |
| 1080 |
|
| 1081 |
|
| 1082 |
|
| 1083 |
|
| 1084 |
filtered_args.pop("vsproj_props_only", None) |
| 1085 |
|
| 1086 |
|
| 1087 |
filtered_args.pop("progress", None) |
| 1088 |
|
| 1089 |
|
| 1090 |
filtered_args.pop("platform", None) |
| 1091 |
filtered_args.pop("target", None) |
| 1092 |
filtered_args.pop("arch", None) |
| 1093 |
|
| 1094 |
platform = env["platform"] |
| 1095 |
target = env["target"] |
| 1096 |
arch = env["arch"] |
| 1097 |
host_arch = detect_arch() |
| 1098 |
|
| 1099 |
host_platform = "windows" |
| 1100 |
if ( |
| 1101 |
sys.platform.startswith("linux") |
| 1102 |
or sys.platform.startswith("dragonfly") |
| 1103 |
or sys.platform.startswith("freebsd") |
| 1104 |
or sys.platform.startswith("netbsd") |
| 1105 |
or sys.platform.startswith("openbsd") |
| 1106 |
): |
| 1107 |
host_platform = "linuxbsd" |
| 1108 |
elif sys.platform == "darwin": |
| 1109 |
host_platform = "macos" |
| 1110 |
|
| 1111 |
vs_configuration = {} |
| 1112 |
host_vs_configuration = {} |
| 1113 |
common_build_prefix = [] |
| 1114 |
confs = [] |
| 1115 |
for x in sorted(glob.glob("platform/*")): |
| 1116 |
|
| 1117 |
if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"): |
| 1118 |
continue |
| 1119 |
tmppath = "./" + x |
| 1120 |
sys.path.insert(0, tmppath) |
| 1121 |
import msvs |
| 1122 |
|
| 1123 |
vs_plats = [] |
| 1124 |
vs_confs = [] |
| 1125 |
try: |
| 1126 |
platform_name = x[9:] |
| 1127 |
vs_plats = msvs.get_platforms() |
| 1128 |
vs_confs = msvs.get_configurations() |
| 1129 |
val = [] |
| 1130 |
for plat in vs_plats: |
| 1131 |
val += [{"platform": plat[0], "architecture": plat[1]}] |
| 1132 |
|
| 1133 |
vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val} |
| 1134 |
confs += [vsconf] |
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
if platform == platform_name: |
| 1139 |
common_build_prefix = msvs.get_build_prefix(env) |
| 1140 |
vs_configuration = vsconf |
| 1141 |
if platform_name == host_platform: |
| 1142 |
host_vs_configuration = vsconf |
| 1143 |
for a in vsconf["arches"]: |
| 1144 |
if host_arch == a["architecture"]: |
| 1145 |
host_arch = a["platform"] |
| 1146 |
break |
| 1147 |
except Exception: |
| 1148 |
pass |
| 1149 |
|
| 1150 |
sys.path.remove(tmppath) |
| 1151 |
sys.modules.pop("msvs") |
| 1152 |
|
| 1153 |
extensions = {} |
| 1154 |
extensions["headers"] = [".h", ".hh", ".hpp", ".hxx", ".inc"] |
| 1155 |
extensions["sources"] = [".c", ".cc", ".cpp", ".cxx", ".m", ".mm", ".java"] |
| 1156 |
extensions["others"] = [".natvis", ".glsl", ".rc"] |
| 1157 |
|
| 1158 |
headers = [] |
| 1159 |
headers_dirs = [] |
| 1160 |
for ext in extensions["headers"]: |
| 1161 |
for file in glob_recursive_2("*" + ext, headers_dirs): |
| 1162 |
headers.append(str(file).replace("/", "\\")) |
| 1163 |
|
| 1164 |
sources = [] |
| 1165 |
sources_dirs = [] |
| 1166 |
for ext in extensions["sources"]: |
| 1167 |
for file in glob_recursive_2("*" + ext, sources_dirs): |
| 1168 |
sources.append(str(file).replace("/", "\\")) |
| 1169 |
|
| 1170 |
others = [] |
| 1171 |
others_dirs = [] |
| 1172 |
for ext in extensions["others"]: |
| 1173 |
for file in glob_recursive_2("*" + ext, others_dirs): |
| 1174 |
others.append(str(file).replace("/", "\\")) |
| 1175 |
|
| 1176 |
skip_filters = False |
| 1177 |
import hashlib |
| 1178 |
import json |
| 1179 |
|
| 1180 |
md5 = hashlib.md5( |
| 1181 |
json.dumps(sorted(headers + headers_dirs + sources + sources_dirs + others + others_dirs)).encode("utf-8") |
| 1182 |
).hexdigest() |
| 1183 |
|
| 1184 |
if os.path.exists(f"{project_name}.vcxproj.filters"): |
| 1185 |
with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file: |
| 1186 |
existing_filters = file.read() |
| 1187 |
match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters) |
| 1188 |
if match is not None and md5 == match.group(1): |
| 1189 |
skip_filters = True |
| 1190 |
|
| 1191 |
import uuid |
| 1192 |
|
| 1193 |
|
| 1194 |
if not skip_filters: |
| 1195 |
print(f"Regenerating {project_name}.vcxproj.filters") |
| 1196 |
|
| 1197 |
with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file: |
| 1198 |
filters_template = file.read() |
| 1199 |
for i in range(1, 10): |
| 1200 |
filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4())) |
| 1201 |
|
| 1202 |
filters = "" |
| 1203 |
|
| 1204 |
for d in headers_dirs: |
| 1205 |
filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n' |
| 1206 |
for d in sources_dirs: |
| 1207 |
filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n' |
| 1208 |
for d in others_dirs: |
| 1209 |
filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n' |
| 1210 |
|
| 1211 |
filters_template = filters_template.replace("%%FILTERS%%", filters) |
| 1212 |
|
| 1213 |
filters = "" |
| 1214 |
for file in headers: |
| 1215 |
filters += ( |
| 1216 |
f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n' |
| 1217 |
) |
| 1218 |
filters_template = filters_template.replace("%%INCLUDES%%", filters) |
| 1219 |
|
| 1220 |
filters = "" |
| 1221 |
for file in sources: |
| 1222 |
filters += ( |
| 1223 |
f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n' |
| 1224 |
) |
| 1225 |
|
| 1226 |
filters_template = filters_template.replace("%%COMPILES%%", filters) |
| 1227 |
|
| 1228 |
filters = "" |
| 1229 |
for file in others: |
| 1230 |
filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n' |
| 1231 |
filters_template = filters_template.replace("%%OTHERS%%", filters) |
| 1232 |
|
| 1233 |
filters_template = filters_template.replace("%%HASH%%", md5) |
| 1234 |
|
| 1235 |
with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f: |
| 1236 |
f.write(filters_template) |
| 1237 |
|
| 1238 |
headers_active = [] |
| 1239 |
sources_active = [] |
| 1240 |
others_active = [] |
| 1241 |
|
| 1242 |
get_dependencies( |
| 1243 |
env.File(f"#bin/godot{env['PROGSUFFIX']}"), env, extensions, headers_active, sources_active, others_active |
| 1244 |
) |
| 1245 |
|
| 1246 |
all_items = [] |
| 1247 |
properties = [] |
| 1248 |
activeItems = [] |
| 1249 |
extraItems = [] |
| 1250 |
|
| 1251 |
set_headers = set(headers_active) |
| 1252 |
set_sources = set(sources_active) |
| 1253 |
set_others = set(others_active) |
| 1254 |
for file in headers: |
| 1255 |
base_path = os.path.dirname(file).replace("\\", "_") |
| 1256 |
all_items.append(f'<ClInclude Include="{file}">') |
| 1257 |
all_items.append( |
| 1258 |
f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>" |
| 1259 |
) |
| 1260 |
all_items.append("</ClInclude>") |
| 1261 |
if file in set_headers: |
| 1262 |
activeItems.append(file) |
| 1263 |
|
| 1264 |
for file in sources: |
| 1265 |
base_path = os.path.dirname(file).replace("\\", "_") |
| 1266 |
all_items.append(f'<ClCompile Include="{file}">') |
| 1267 |
all_items.append( |
| 1268 |
f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>" |
| 1269 |
) |
| 1270 |
all_items.append("</ClCompile>") |
| 1271 |
if file in set_sources: |
| 1272 |
activeItems.append(file) |
| 1273 |
|
| 1274 |
for file in others: |
| 1275 |
base_path = os.path.dirname(file).replace("\\", "_") |
| 1276 |
all_items.append(f'<None Include="{file}">') |
| 1277 |
all_items.append( |
| 1278 |
f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>" |
| 1279 |
) |
| 1280 |
all_items.append("</None>") |
| 1281 |
if file in set_others: |
| 1282 |
activeItems.append(file) |
| 1283 |
|
| 1284 |
if vs_configuration: |
| 1285 |
vsconf = "" |
| 1286 |
for a in vs_configuration["arches"]: |
| 1287 |
if arch == a["architecture"]: |
| 1288 |
vsconf = f"{target}|{a['platform']}" |
| 1289 |
break |
| 1290 |
|
| 1291 |
condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'" |
| 1292 |
itemlist = {} |
| 1293 |
for item in activeItems: |
| 1294 |
key = os.path.dirname(item).replace("\\", "_") |
| 1295 |
if key not in itemlist: |
| 1296 |
itemlist[key] = [item] |
| 1297 |
else: |
| 1298 |
itemlist[key] += [item] |
| 1299 |
|
| 1300 |
for x in itemlist.keys(): |
| 1301 |
properties.append( |
| 1302 |
"<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x) |
| 1303 |
) |
| 1304 |
output = os.path.join("bin", f"godot{env['PROGSUFFIX']}") |
| 1305 |
|
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
env.Append(VSHINT_DEFINES=[f"MODULE_{module.upper()}_ENABLED" for module in env.module_list]) |
| 1310 |
|
| 1311 |
with open("misc/msvs/props.template", "r", encoding="utf-8") as file: |
| 1312 |
props_template = file.read() |
| 1313 |
|
| 1314 |
props_template = props_template.replace("%%CONDITION%%", condition) |
| 1315 |
props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties)) |
| 1316 |
props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems)) |
| 1317 |
|
| 1318 |
props_template = props_template.replace("%%OUTPUT%%", output) |
| 1319 |
|
| 1320 |
proplist = [format_key_value(j) for j in list(env["CPPDEFINES"])] |
| 1321 |
proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])] |
| 1322 |
props_template = props_template.replace("%%DEFINES%%", ";".join(proplist)) |
| 1323 |
|
| 1324 |
proplist = [str(j) for j in env["CPPPATH"]] |
| 1325 |
proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])] |
| 1326 |
proplist += [str(j) for j in get_default_include_paths(env)] |
| 1327 |
props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist)) |
| 1328 |
|
| 1329 |
proplist = [env.subst("$CCFLAGS")] |
| 1330 |
proplist += [env.subst("$CXXFLAGS")] |
| 1331 |
proplist += [env.subst("$VSHINT_OPTIONS")] |
| 1332 |
props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist)) |
| 1333 |
|
| 1334 |
|
| 1335 |
|
| 1336 |
|
| 1337 |
|
| 1338 |
common_build_postfix = [ |
| 1339 |
"--directory="$(ProjectDir.TrimEnd('\\'))"", |
| 1340 |
"progress=no", |
| 1341 |
f"platform={platform}", |
| 1342 |
f"target={target}", |
| 1343 |
f"arch={arch}", |
| 1344 |
] |
| 1345 |
|
| 1346 |
for arg, value in filtered_args.items(): |
| 1347 |
common_build_postfix.append(f"{arg}={value}") |
| 1348 |
|
| 1349 |
cmd_rebuild = [ |
| 1350 |
"vsproj=yes", |
| 1351 |
"vsproj_props_only=yes", |
| 1352 |
"vsproj_gen_only=no", |
| 1353 |
f"vsproj_name={project_name}", |
| 1354 |
] + common_build_postfix |
| 1355 |
|
| 1356 |
cmd_clean = [ |
| 1357 |
"--clean", |
| 1358 |
] + common_build_postfix |
| 1359 |
|
| 1360 |
commands = "scons" |
| 1361 |
if len(common_build_prefix) == 0: |
| 1362 |
commands = "echo Starting SCons & " + commands |
| 1363 |
else: |
| 1364 |
common_build_prefix[0] = "echo Starting SCons & " + common_build_prefix[0] |
| 1365 |
|
| 1366 |
cmd = " ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)]) |
| 1367 |
props_template = props_template.replace("%%BUILD%%", cmd) |
| 1368 |
|
| 1369 |
cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)]) |
| 1370 |
props_template = props_template.replace("%%REBUILD%%", cmd) |
| 1371 |
|
| 1372 |
cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_clean)]) |
| 1373 |
props_template = props_template.replace("%%CLEAN%%", cmd) |
| 1374 |
|
| 1375 |
with open( |
| 1376 |
f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n" |
| 1377 |
) as f: |
| 1378 |
f.write(props_template) |
| 1379 |
|
| 1380 |
proj_uuid = str(uuid.uuid4()) |
| 1381 |
sln_uuid = str(uuid.uuid4()) |
| 1382 |
|
| 1383 |
if os.path.exists(f"{project_name}.sln"): |
| 1384 |
for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines(): |
| 1385 |
if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'): |
| 1386 |
proj_uuid = re.search( |
| 1387 |
r"\"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}\"$", |
| 1388 |
line, |
| 1389 |
).group(1) |
| 1390 |
elif line.strip().startswith("SolutionGuid ="): |
| 1391 |
sln_uuid = re.search( |
| 1392 |
r"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}", line |
| 1393 |
).group(1) |
| 1394 |
break |
| 1395 |
|
| 1396 |
configurations = [] |
| 1397 |
imports = [] |
| 1398 |
properties = [] |
| 1399 |
section1 = [] |
| 1400 |
section2 = [] |
| 1401 |
for conf in confs: |
| 1402 |
godot_platform = conf["platform"] |
| 1403 |
has_editor = "editor" in conf["targets"] |
| 1404 |
|
| 1405 |
|
| 1406 |
|
| 1407 |
|
| 1408 |
|
| 1409 |
|
| 1410 |
|
| 1411 |
|
| 1412 |
|
| 1413 |
|
| 1414 |
|
| 1415 |
if has_editor and godot_platform != host_vs_configuration["platform"]: |
| 1416 |
continue |
| 1417 |
|
| 1418 |
for p in conf["arches"]: |
| 1419 |
sln_plat = p["platform"] |
| 1420 |
proj_plat = sln_plat |
| 1421 |
godot_arch = p["architecture"] |
| 1422 |
|
| 1423 |
|
| 1424 |
|
| 1425 |
|
| 1426 |
if not has_editor: |
| 1427 |
section1 += [f"editor|{sln_plat} = editor|{proj_plat}"] |
| 1428 |
section2 += [f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{host_arch}"] |
| 1429 |
|
| 1430 |
configurations += [ |
| 1431 |
f'<ProjectConfiguration Include="editor|{proj_plat}">', |
| 1432 |
" <Configuration>editor</Configuration>", |
| 1433 |
f" <Platform>{proj_plat}</Platform>", |
| 1434 |
"</ProjectConfiguration>", |
| 1435 |
] |
| 1436 |
|
| 1437 |
properties += [ |
| 1438 |
f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">", |
| 1439 |
" <GodotConfiguration>editor</GodotConfiguration>", |
| 1440 |
f" <GodotPlatform>{proj_plat}</GodotPlatform>", |
| 1441 |
"</PropertyGroup>", |
| 1442 |
] |
| 1443 |
|
| 1444 |
for t in conf["targets"]: |
| 1445 |
godot_target = t |
| 1446 |
|
| 1447 |
|
| 1448 |
if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32": |
| 1449 |
sln_plat = "x86" |
| 1450 |
|
| 1451 |
configurations += [ |
| 1452 |
f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">', |
| 1453 |
f" <Configuration>{godot_target}</Configuration>", |
| 1454 |
f" <Platform>{proj_plat}</Platform>", |
| 1455 |
"</ProjectConfiguration>", |
| 1456 |
] |
| 1457 |
|
| 1458 |
properties += [ |
| 1459 |
f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">", |
| 1460 |
f" <GodotConfiguration>{godot_target}</GodotConfiguration>", |
| 1461 |
f" <GodotPlatform>{proj_plat}</GodotPlatform>", |
| 1462 |
"</PropertyGroup>", |
| 1463 |
] |
| 1464 |
|
| 1465 |
p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props" |
| 1466 |
imports += [ |
| 1467 |
f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>' |
| 1468 |
] |
| 1469 |
|
| 1470 |
section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"] |
| 1471 |
|
| 1472 |
section2 += [ |
| 1473 |
f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}", |
| 1474 |
f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}", |
| 1475 |
] |
| 1476 |
|
| 1477 |
|
| 1478 |
imports += [ |
| 1479 |
f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>' |
| 1480 |
] |
| 1481 |
section1 = sorted(section1) |
| 1482 |
section2 = sorted(section2) |
| 1483 |
|
| 1484 |
if not get_bool(original_args, "vsproj_props_only", False): |
| 1485 |
with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file: |
| 1486 |
proj_template = file.read() |
| 1487 |
proj_template = proj_template.replace("%%UUID%%", proj_uuid) |
| 1488 |
proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations)) |
| 1489 |
proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports)) |
| 1490 |
proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items)) |
| 1491 |
proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties)) |
| 1492 |
|
| 1493 |
with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f: |
| 1494 |
f.write(proj_template) |
| 1495 |
|
| 1496 |
if not get_bool(original_args, "vsproj_props_only", False): |
| 1497 |
with open("misc/msvs/sln.template", "r", encoding="utf-8") as file: |
| 1498 |
sln_template = file.read() |
| 1499 |
sln_template = sln_template.replace("%%NAME%%", project_name) |
| 1500 |
sln_template = sln_template.replace("%%UUID%%", proj_uuid) |
| 1501 |
sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid) |
| 1502 |
sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1)) |
| 1503 |
sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2)) |
| 1504 |
|
| 1505 |
with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f: |
| 1506 |
f.write(sln_template) |
| 1507 |
|
| 1508 |
if get_bool(original_args, "vsproj_gen_only", True): |
| 1509 |
sys.exit() |
| 1510 |
|
| 1511 |
|
| 1512 |
|
| 1513 |
|
| 1514 |
|
| 1515 |
|
| 1516 |
|
| 1517 |
def generate_copyright_header(filename: str) -> str: |
| 1518 |
MARGIN = 70 |
| 1519 |
TEMPLATE = """\ |
| 1520 |
/**************************************************************************/ |
| 1521 |
/* %s*/ |
| 1522 |
/**************************************************************************/ |
| 1523 |
/* This file is part of: */ |
| 1524 |
/* GODOT ENGINE */ |
| 1525 |
/* https://godotengine.org */ |
| 1526 |
/**************************************************************************/ |
| 1527 |
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ |
| 1528 |
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ |
| 1529 |
/* */ |
| 1530 |
/* Permission is hereby granted, free of charge, to any person obtaining */ |
| 1531 |
/* a copy of this software and associated documentation files (the */ |
| 1532 |
/* "Software"), to deal in the Software without restriction, including */ |
| 1533 |
/* without limitation the rights to use, copy, modify, merge, publish, */ |
| 1534 |
/* distribute, sublicense, and/or sell copies of the Software, and to */ |
| 1535 |
/* permit persons to whom the Software is furnished to do so, subject to */ |
| 1536 |
/* the following conditions: */ |
| 1537 |
/* */ |
| 1538 |
/* The above copyright notice and this permission notice shall be */ |
| 1539 |
/* included in all copies or substantial portions of the Software. */ |
| 1540 |
/* */ |
| 1541 |
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ |
| 1542 |
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ |
| 1543 |
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ |
| 1544 |
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ |
| 1545 |
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ |
| 1546 |
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ |
| 1547 |
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ |
| 1548 |
/**************************************************************************/ |
| 1549 |
""" |
| 1550 |
if len(filename := os.path.basename(filename).ljust(MARGIN)) > MARGIN: |
| 1551 |
print_warning(f'Filename "{filename}" too large for copyright header.') |
| 1552 |
return TEMPLATE % filename |
| 1553 |
|
| 1554 |
|
| 1555 |
@contextlib.contextmanager |
| 1556 |
def generated_wrapper( |
| 1557 |
path: str, |
| 1558 |
guard: bool | None = None, |
| 1559 |
) -> Generator[TextIO, None, None]: |
| 1560 |
""" |
| 1561 |
Wrapper class to automatically handle copyright headers and header guards |
| 1562 |
for generated scripts. Meant to be invoked via `with` statement similar to |
| 1563 |
creating a file. |
| 1564 |
|
| 1565 |
- `path`: The path of the file to be created. |
| 1566 |
- `guard`: Optional bool to determine if `#pragma once` should be added. If |
| 1567 |
unassigned, the value is determined by file extension. |
| 1568 |
""" |
| 1569 |
|
| 1570 |
with open(path, "wt", encoding="utf-8", newline="\n") as file: |
| 1571 |
if not path.endswith(".out"): |
| 1572 |
file.write(generate_copyright_header(path)) |
| 1573 |
file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n") |
| 1574 |
|
| 1575 |
if guard is None: |
| 1576 |
guard = path.endswith((".h", ".hh", ".hpp", ".hxx", ".inc")) |
| 1577 |
if guard: |
| 1578 |
file.write("#pragma once\n\n") |
| 1579 |
|
| 1580 |
with StringIO(newline="\n") as str_io: |
| 1581 |
yield str_io |
| 1582 |
file.write(str_io.getvalue().strip() or "/* NO CONTENT */") |
| 1583 |
|
| 1584 |
file.write("\n") |
| 1585 |
|
| 1586 |
|
| 1587 |
def get_buffer(path: str) -> bytes: |
| 1588 |
with open(path, "rb") as file: |
| 1589 |
return file.read() |
| 1590 |
|
| 1591 |
|
| 1592 |
def compress_buffer(buffer: bytes) -> bytes: |
| 1593 |
|
| 1594 |
|
| 1595 |
return zlib.compress(buffer, zlib.Z_BEST_COMPRESSION) |
| 1596 |
|
| 1597 |
|
| 1598 |
def format_buffer(buffer: bytes, indent: int = 0, width: int = 120, initial_indent: bool = False) -> str: |
| 1599 |
return textwrap.fill( |
| 1600 |
", ".join(str(byte) for byte in buffer), |
| 1601 |
width=width, |
| 1602 |
initial_indent="\t" * indent if initial_indent else "", |
| 1603 |
subsequent_indent="\t" * indent, |
| 1604 |
tabsize=4, |
| 1605 |
) |
| 1606 |
|
| 1607 |
|
| 1608 |
|
| 1609 |
|
| 1610 |
|
| 1611 |
|
| 1612 |
C_ESCAPABLES = [ |
| 1613 |
("\\", "\\\\"), |
| 1614 |
("\a", "\\a"), |
| 1615 |
("\b", "\\b"), |
| 1616 |
("\f", "\\f"), |
| 1617 |
("\n", "\\n"), |
| 1618 |
("\r", "\\r"), |
| 1619 |
("\t", "\\t"), |
| 1620 |
("\v", "\\v"), |
| 1621 |
|
| 1622 |
('"', '\\"'), |
| 1623 |
] |
| 1624 |
C_ESCAPE_TABLE = str.maketrans(dict((x, y) for x, y in C_ESCAPABLES)) |
| 1625 |
|
| 1626 |
|
| 1627 |
def to_escaped_cstring(value: str) -> str: |
| 1628 |
return value.translate(C_ESCAPE_TABLE) |
| 1629 |
|
| 1630 |
|
| 1631 |
def to_raw_cstring(value: str | list[str]) -> str: |
| 1632 |
MAX_LITERAL = 16 * 1024 |
| 1633 |
|
| 1634 |
if isinstance(value, list): |
| 1635 |
value = "\n".join(value) + "\n" |
| 1636 |
|
| 1637 |
split: list[bytes] = [] |
| 1638 |
offset = 0 |
| 1639 |
encoded = value.encode() |
| 1640 |
|
| 1641 |
while offset <= len(encoded): |
| 1642 |
segment = encoded[offset : offset + MAX_LITERAL] |
| 1643 |
offset += MAX_LITERAL |
| 1644 |
if len(segment) == MAX_LITERAL: |
| 1645 |
|
| 1646 |
pretty_break = segment.rfind(b"\n\n") |
| 1647 |
if pretty_break != -1: |
| 1648 |
segment = segment[: pretty_break + 1] |
| 1649 |
offset -= MAX_LITERAL - pretty_break - 1 |
| 1650 |
|
| 1651 |
|
| 1652 |
elif segment[-1] & 0b10000000: |
| 1653 |
last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0] |
| 1654 |
last_11xxxxxx = segment[last_11xxxxxx_index] |
| 1655 |
if not last_11xxxxxx & 0b00100000: |
| 1656 |
last_char_length = 2 |
| 1657 |
elif not last_11xxxxxx & 0b0010000: |
| 1658 |
last_char_length = 3 |
| 1659 |
elif not last_11xxxxxx & 0b0001000: |
| 1660 |
last_char_length = 4 |
| 1661 |
|
| 1662 |
if last_char_length > -last_11xxxxxx_index: |
| 1663 |
segment = segment[:last_11xxxxxx_index] |
| 1664 |
offset += last_11xxxxxx_index |
| 1665 |
|
| 1666 |
split += [segment] |
| 1667 |
|
| 1668 |
if len(split) == 1: |
| 1669 |
return f'R"<!>({split[0].decode()})<!>"' |
| 1670 |
else: |
| 1671 |
|
| 1672 |
return "({})".format(" ".join(f'R"<!>({segment.decode()})<!>"' for segment in split)) |
| 1673 |
|
| 1674 |
|
| 1675 |
def get_default_include_paths(env): |
| 1676 |
if env.msvc: |
| 1677 |
return [] |
| 1678 |
compiler = env.subst("$CXX") |
| 1679 |
target = os.path.join(env.Dir("#main").abspath, "main.cpp") |
| 1680 |
args = [compiler, target, "-x", "c++", "-v"] |
| 1681 |
ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) |
| 1682 |
output = ret.stdout |
| 1683 |
match = re.search(r"#include <\.\.\.> search starts here:([\S\s]*)End of search list.", output) |
| 1684 |
if not match: |
| 1685 |
print_warning("Failed to find the include paths in the compiler output.") |
| 1686 |
return [] |
| 1687 |
return [x.strip() for x in match[1].strip().splitlines()] |