methods.py 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. import contextlib
  2. import glob
  3. import os
  4. import re
  5. import subprocess
  6. import sys
  7. from collections import OrderedDict
  8. from enum import Enum
  9. from io import StringIO, TextIOWrapper
  10. from pathlib import Path
  11. from typing import Generator, List, Optional, Union
  12. # Get the "Godot" folder name ahead of time
  13. base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/"
  14. base_folder_only = os.path.basename(os.path.normpath(base_folder_path))
  15. # Listing all the folders we have converted
  16. # for SCU in scu_builders.py
  17. _scu_folders = set()
  18. # Colors are disabled in non-TTY environments such as pipes. This means
  19. # that if output is redirected to a file, it won't contain color codes.
  20. # Colors are always enabled on continuous integration.
  21. _colorize = bool(sys.stdout.isatty() or os.environ.get("CI"))
  22. def set_scu_folders(scu_folders):
  23. global _scu_folders
  24. _scu_folders = scu_folders
  25. class ANSI(Enum):
  26. """
  27. Enum class for adding ansi colorcodes directly into strings.
  28. Automatically converts values to strings representing their
  29. internal value, or an empty string in a non-colorized scope.
  30. """
  31. RESET = "\x1b[0m"
  32. BOLD = "\x1b[1m"
  33. ITALIC = "\x1b[3m"
  34. UNDERLINE = "\x1b[4m"
  35. STRIKETHROUGH = "\x1b[9m"
  36. REGULAR = "\x1b[22;23;24;29m"
  37. BLACK = "\x1b[30m"
  38. RED = "\x1b[31m"
  39. GREEN = "\x1b[32m"
  40. YELLOW = "\x1b[33m"
  41. BLUE = "\x1b[34m"
  42. MAGENTA = "\x1b[35m"
  43. CYAN = "\x1b[36m"
  44. WHITE = "\x1b[37m"
  45. PURPLE = "\x1b[38;5;93m"
  46. PINK = "\x1b[38;5;206m"
  47. ORANGE = "\x1b[38;5;214m"
  48. GRAY = "\x1b[38;5;244m"
  49. def __str__(self) -> str:
  50. global _colorize
  51. return str(self.value) if _colorize else ""
  52. def print_warning(*values: object) -> None:
  53. """Prints a warning message with formatting."""
  54. print(f"{ANSI.YELLOW}{ANSI.BOLD}WARNING:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  55. def print_error(*values: object) -> None:
  56. """Prints an error message with formatting."""
  57. print(f"{ANSI.RED}{ANSI.BOLD}ERROR:{ANSI.REGULAR}", *values, ANSI.RESET, file=sys.stderr)
  58. def add_source_files_orig(self, sources, files, allow_gen=False):
  59. # Convert string to list of absolute paths (including expanding wildcard)
  60. if isinstance(files, (str, bytes)):
  61. # Keep SCons project-absolute path as they are (no wildcard support)
  62. if files.startswith("#"):
  63. if "*" in files:
  64. print_error("Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  65. return
  66. files = [files]
  67. else:
  68. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  69. # They should instead be added manually.
  70. skip_gen_cpp = "*" in files
  71. dir_path = self.Dir(".").abspath
  72. files = sorted(glob.glob(dir_path + "/" + files))
  73. if skip_gen_cpp and not allow_gen:
  74. files = [f for f in files if not f.endswith(".gen.cpp")]
  75. # Add each path as compiled Object following environment (self) configuration
  76. for path in files:
  77. obj = self.Object(path)
  78. if obj in sources:
  79. print_warning('Object "{}" already included in environment sources.'.format(obj))
  80. continue
  81. sources.append(obj)
  82. # The section name is used for checking
  83. # the hash table to see whether the folder
  84. # is included in the SCU build.
  85. # It will be something like "core/math".
  86. def _find_scu_section_name(subdir):
  87. section_path = os.path.abspath(subdir) + "/"
  88. folders = []
  89. folder = ""
  90. for i in range(8):
  91. folder = os.path.dirname(section_path)
  92. folder = os.path.basename(folder)
  93. if folder == base_folder_only:
  94. break
  95. folders += [folder]
  96. section_path += "../"
  97. section_path = os.path.abspath(section_path) + "/"
  98. section_name = ""
  99. for n in range(len(folders)):
  100. # section_name += folders[len(folders) - n - 1] + " "
  101. section_name += folders[len(folders) - n - 1]
  102. if n != (len(folders) - 1):
  103. section_name += "/"
  104. return section_name
  105. def add_source_files_scu(self, sources, files, allow_gen=False):
  106. if self["scu_build"] and isinstance(files, str):
  107. if "*." not in files:
  108. return False
  109. # If the files are in a subdirectory, we want to create the scu gen
  110. # files inside this subdirectory.
  111. subdir = os.path.dirname(files)
  112. if subdir != "":
  113. subdir += "/"
  114. section_name = _find_scu_section_name(subdir)
  115. # if the section name is in the hash table?
  116. # i.e. is it part of the SCU build?
  117. global _scu_folders
  118. if section_name not in (_scu_folders):
  119. return False
  120. # Add all the gen.cpp files in the SCU directory
  121. add_source_files_orig(self, sources, subdir + "scu/scu_*.gen.cpp", True)
  122. return True
  123. return False
  124. # Either builds the folder using the SCU system,
  125. # or reverts to regular build.
  126. def add_source_files(self, sources, files, allow_gen=False):
  127. if not add_source_files_scu(self, sources, files, allow_gen):
  128. # Wraps the original function when scu build is not active.
  129. add_source_files_orig(self, sources, files, allow_gen)
  130. return False
  131. return True
  132. def disable_warnings(self):
  133. # 'self' is the environment
  134. if self.msvc and not using_clang(self):
  135. # We have to remove existing warning level defines before appending /w,
  136. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  137. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  138. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  139. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  140. self.AppendUnique(CCFLAGS=["/w"])
  141. else:
  142. self.AppendUnique(CCFLAGS=["-w"])
  143. def force_optimization_on_debug(self):
  144. # 'self' is the environment
  145. if self["target"] == "template_release":
  146. return
  147. if self.msvc:
  148. # We have to remove existing optimization level defines before appending /O2,
  149. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  150. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  151. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  152. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  153. self.AppendUnique(CCFLAGS=["/O2"])
  154. else:
  155. self.AppendUnique(CCFLAGS=["-O3"])
  156. def add_module_version_string(self, s):
  157. self.module_version_string += "." + s
  158. def get_version_info(module_version_string="", silent=False):
  159. build_name = "custom_build"
  160. if os.getenv("BUILD_NAME") is not None:
  161. build_name = str(os.getenv("BUILD_NAME"))
  162. if not silent:
  163. print(f"Using custom build name: '{build_name}'.")
  164. import version
  165. version_info = {
  166. "short_name": str(version.short_name),
  167. "name": str(version.name),
  168. "major": int(version.major),
  169. "minor": int(version.minor),
  170. "patch": int(version.patch),
  171. "status": str(version.status),
  172. "build": str(build_name),
  173. "module_config": str(version.module_config) + module_version_string,
  174. "website": str(version.website),
  175. "docs_branch": str(version.docs),
  176. }
  177. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  178. # so this define provides a way to override it without having to modify the source.
  179. if os.getenv("GODOT_VERSION_STATUS") is not None:
  180. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  181. if not silent:
  182. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  183. # Parse Git hash if we're in a Git repo.
  184. githash = ""
  185. gitfolder = ".git"
  186. if os.path.isfile(".git"):
  187. with open(".git", "r", encoding="utf-8") as file:
  188. module_folder = file.readline().strip()
  189. if module_folder.startswith("gitdir: "):
  190. gitfolder = module_folder[8:]
  191. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  192. with open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8") as file:
  193. head = file.readline().strip()
  194. if head.startswith("ref: "):
  195. ref = head[5:]
  196. # If this directory is a Git worktree instead of a root clone.
  197. parts = gitfolder.split("/")
  198. if len(parts) > 2 and parts[-2] == "worktrees":
  199. gitfolder = "/".join(parts[0:-2])
  200. head = os.path.join(gitfolder, ref)
  201. packedrefs = os.path.join(gitfolder, "packed-refs")
  202. if os.path.isfile(head):
  203. with open(head, "r", encoding="utf-8") as file:
  204. githash = file.readline().strip()
  205. elif os.path.isfile(packedrefs):
  206. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  207. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  208. for line in open(packedrefs, "r", encoding="utf-8").read().splitlines():
  209. if line.startswith("#"):
  210. continue
  211. (line_hash, line_ref) = line.split(" ")
  212. if ref == line_ref:
  213. githash = line_hash
  214. break
  215. else:
  216. githash = head
  217. version_info["git_hash"] = githash
  218. # Fallback to 0 as a timestamp (will be treated as "unknown" in the engine).
  219. version_info["git_timestamp"] = 0
  220. # Get the UNIX timestamp of the build commit.
  221. if os.path.exists(".git"):
  222. try:
  223. version_info["git_timestamp"] = subprocess.check_output(
  224. ["git", "log", "-1", "--pretty=format:%ct", "--no-show-signature", githash]
  225. ).decode("utf-8")
  226. except (subprocess.CalledProcessError, OSError):
  227. # `git` not found in PATH.
  228. pass
  229. return version_info
  230. def parse_cg_file(fname, uniforms, sizes, conditionals):
  231. with open(fname, "r", encoding="utf-8") as fs:
  232. line = fs.readline()
  233. while line:
  234. if re.match(r"^\s*uniform", line):
  235. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  236. type = res.groups(1)
  237. name = res.groups(2)
  238. uniforms.append(name)
  239. if type.find("texobj") != -1:
  240. sizes.append(1)
  241. else:
  242. t = re.match(r"float(\d)x(\d)", type)
  243. if t:
  244. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  245. else:
  246. t = re.match(r"float(\d)", type)
  247. sizes.append(int(t.groups(1)))
  248. if line.find("[branch]") != -1:
  249. conditionals.append(name)
  250. line = fs.readline()
  251. def get_cmdline_bool(option, default):
  252. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  253. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  254. """
  255. from SCons.Script import ARGUMENTS
  256. from SCons.Variables.BoolVariable import _text2bool
  257. cmdline_val = ARGUMENTS.get(option)
  258. if cmdline_val is not None:
  259. return _text2bool(cmdline_val)
  260. else:
  261. return default
  262. def detect_modules(search_path, recursive=False):
  263. """Detects and collects a list of C++ modules at specified path
  264. `search_path` - a directory path containing modules. The path may point to
  265. a single module, which may have other nested modules. A module must have
  266. "register_types.h", "SCsub", "config.py" files created to be detected.
  267. `recursive` - if `True`, then all subdirectories are searched for modules as
  268. specified by the `search_path`, otherwise collects all modules under the
  269. `search_path` directory. If the `search_path` is a module, it is collected
  270. in all cases.
  271. Returns an `OrderedDict` with module names as keys, and directory paths as
  272. values. If a path is relative, then it is a built-in module. If a path is
  273. absolute, then it is a custom module collected outside of the engine source.
  274. """
  275. modules = OrderedDict()
  276. def add_module(path):
  277. module_name = os.path.basename(path)
  278. module_path = path.replace("\\", "/") # win32
  279. modules[module_name] = module_path
  280. def is_engine(path):
  281. # Prevent recursively detecting modules in self and other
  282. # Godot sources when using `custom_modules` build option.
  283. version_path = os.path.join(path, "version.py")
  284. if os.path.exists(version_path):
  285. with open(version_path, "r", encoding="utf-8") as f:
  286. if 'short_name = "godot"' in f.read():
  287. return True
  288. return False
  289. def get_files(path):
  290. files = glob.glob(os.path.join(path, "*"))
  291. # Sort so that `register_module_types` does not change that often,
  292. # and plugins are registered in alphabetic order as well.
  293. files.sort()
  294. return files
  295. if not recursive:
  296. if is_module(search_path):
  297. add_module(search_path)
  298. for path in get_files(search_path):
  299. if is_engine(path):
  300. continue
  301. if is_module(path):
  302. add_module(path)
  303. else:
  304. to_search = [search_path]
  305. while to_search:
  306. path = to_search.pop()
  307. if is_module(path):
  308. add_module(path)
  309. for child in get_files(path):
  310. if not os.path.isdir(child):
  311. continue
  312. if is_engine(child):
  313. continue
  314. to_search.insert(0, child)
  315. return modules
  316. def is_module(path):
  317. if not os.path.isdir(path):
  318. return False
  319. must_exist = ["register_types.h", "SCsub", "config.py"]
  320. for f in must_exist:
  321. if not os.path.exists(os.path.join(path, f)):
  322. return False
  323. return True
  324. def convert_custom_modules_path(path):
  325. if not path:
  326. return path
  327. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  328. err_msg = "Build option 'custom_modules' must %s"
  329. if not os.path.isdir(path):
  330. raise ValueError(err_msg % "point to an existing directory.")
  331. if path == os.path.realpath("modules"):
  332. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  333. return path
  334. def module_add_dependencies(self, module, dependencies, optional=False):
  335. """
  336. Adds dependencies for a given module.
  337. Meant to be used in module `can_build` methods.
  338. """
  339. if module not in self.module_dependencies:
  340. self.module_dependencies[module] = [[], []]
  341. if optional:
  342. self.module_dependencies[module][1].extend(dependencies)
  343. else:
  344. self.module_dependencies[module][0].extend(dependencies)
  345. def module_check_dependencies(self, module):
  346. """
  347. Checks if module dependencies are enabled for a given module,
  348. and prints a warning if they aren't.
  349. Meant to be used in module `can_build` methods.
  350. Returns a boolean (True if dependencies are satisfied).
  351. """
  352. missing_deps = set()
  353. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  354. for dep in required_deps:
  355. opt = "module_{}_enabled".format(dep)
  356. if opt not in self or not self[opt] or not module_check_dependencies(self, dep):
  357. missing_deps.add(dep)
  358. if missing_deps:
  359. if module not in self.disabled_modules:
  360. print_warning(
  361. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  362. module, ", ".join(missing_deps)
  363. )
  364. )
  365. self.disabled_modules.add(module)
  366. return False
  367. else:
  368. return True
  369. def sort_module_list(env):
  370. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  371. frontier = list(env.module_list.keys())
  372. explored = []
  373. while len(frontier):
  374. cur = frontier.pop()
  375. deps_list = deps[cur] if cur in deps else []
  376. if len(deps_list) and any([d not in explored for d in deps_list]):
  377. # Will explore later, after its dependencies
  378. frontier.insert(0, cur)
  379. continue
  380. explored.append(cur)
  381. for k in explored:
  382. env.module_list.move_to_end(k)
  383. def use_windows_spawn_fix(self, platform=None):
  384. if os.name != "nt":
  385. return # not needed, only for windows
  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. if sys.version_info >= (3, 7, 0):
  398. popen_args["text"] = True
  399. proc = subprocess.Popen(cmdline, **popen_args)
  400. _, err = proc.communicate()
  401. rv = proc.wait()
  402. if rv:
  403. print_error(err)
  404. elif len(err) > 0 and not err.isspace():
  405. print(err)
  406. return rv
  407. def mySpawn(sh, escape, cmd, args, env):
  408. # Used by TEMPFILE.
  409. if cmd == "del":
  410. os.remove(args[1])
  411. return 0
  412. newargs = " ".join(args[1:])
  413. cmdline = cmd + " " + newargs
  414. rv = 0
  415. env = {str(key): str(value) for key, value in iter(env.items())}
  416. rv = mySubProcess(cmdline, env)
  417. return rv
  418. self["SPAWN"] = mySpawn
  419. def no_verbose(env):
  420. colors = [ANSI.BLUE, ANSI.BOLD, ANSI.REGULAR, ANSI.RESET]
  421. # There is a space before "..." to ensure that source file names can be
  422. # Ctrl + clicked in the VS Code terminal.
  423. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  424. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors)
  425. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors)
  426. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors)
  427. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors)
  428. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors)
  429. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors)
  430. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors)
  431. compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors)
  432. zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors)
  433. generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors)
  434. env["CXXCOMSTR"] = compile_source_message
  435. env["CCCOMSTR"] = compile_source_message
  436. env["SHCCCOMSTR"] = compile_shared_source_message
  437. env["SHCXXCOMSTR"] = compile_shared_source_message
  438. env["ARCOMSTR"] = link_library_message
  439. env["RANLIBCOMSTR"] = ranlib_library_message
  440. env["SHLINKCOMSTR"] = link_shared_library_message
  441. env["LINKCOMSTR"] = link_program_message
  442. env["JARCOMSTR"] = java_library_message
  443. env["JAVACCOMSTR"] = java_compile_source_message
  444. env["RCCOMSTR"] = compiled_resource_message
  445. env["ZIPCOMSTR"] = zip_archive_message
  446. env["GENCOMSTR"] = generated_file_message
  447. def detect_visual_c_compiler_version(tools_env):
  448. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  449. # (see the SCons documentation for more information on what it does)...
  450. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  451. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  452. # the proper vc version that will be called
  453. # There is no flag to give to visual c compilers to set the architecture, i.e. scons arch argument (x86_32, x86_64, arm64, etc.).
  454. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  455. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  456. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  457. # the following string values:
  458. # "" Compiler not detected
  459. # "amd64" Native 64 bit compiler
  460. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  461. # "x86" Native 32 bit compiler
  462. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  463. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  464. # and similar architectures/compilers
  465. # Set chosen compiler to "not detected"
  466. vc_chosen_compiler_index = -1
  467. vc_chosen_compiler_str = ""
  468. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  469. if "VCINSTALLDIR" in tools_env:
  470. # print("Checking VCINSTALLDIR")
  471. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  472. # First test if amd64 and amd64_x86 compilers are present in the path
  473. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  474. if vc_amd64_compiler_detection_index > -1:
  475. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  476. vc_chosen_compiler_str = "amd64"
  477. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  478. if vc_amd64_x86_compiler_detection_index > -1 and (
  479. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  480. ):
  481. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  482. vc_chosen_compiler_str = "amd64_x86"
  483. # Now check the 32 bit compilers
  484. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  485. if vc_x86_compiler_detection_index > -1 and (
  486. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  487. ):
  488. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  489. vc_chosen_compiler_str = "x86"
  490. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  491. if vc_x86_amd64_compiler_detection_index > -1 and (
  492. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  493. ):
  494. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  495. vc_chosen_compiler_str = "x86_amd64"
  496. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  497. if "VCTOOLSINSTALLDIR" in tools_env:
  498. # Newer versions have a different path available
  499. vc_amd64_compiler_detection_index = (
  500. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  501. )
  502. if vc_amd64_compiler_detection_index > -1:
  503. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  504. vc_chosen_compiler_str = "amd64"
  505. vc_amd64_x86_compiler_detection_index = (
  506. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  507. )
  508. if vc_amd64_x86_compiler_detection_index > -1 and (
  509. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  510. ):
  511. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  512. vc_chosen_compiler_str = "amd64_x86"
  513. vc_x86_compiler_detection_index = (
  514. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  515. )
  516. if vc_x86_compiler_detection_index > -1 and (
  517. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  518. ):
  519. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  520. vc_chosen_compiler_str = "x86"
  521. vc_x86_amd64_compiler_detection_index = (
  522. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  523. )
  524. if vc_x86_amd64_compiler_detection_index > -1 and (
  525. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  526. ):
  527. vc_chosen_compiler_str = "x86_amd64"
  528. return vc_chosen_compiler_str
  529. def find_visual_c_batch_file(env):
  530. # TODO: We should investigate if we can avoid relying on SCons internals here.
  531. from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target
  532. msvc_version = get_default_version(env)
  533. # Syntax changed in SCons 4.4.0.
  534. if env.scons_version >= (4, 4, 0):
  535. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  536. else:
  537. (host_platform, target_platform, _) = get_host_target(env)
  538. if env.scons_version < (4, 6, 0):
  539. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  540. # SCons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  541. # then pass that as the last param instead of env as the first param as before.
  542. # Param names need to be explicit, as they were shuffled around in SCons 4.8.0.
  543. product_dir = find_vc_pdir(msvc_version=msvc_version, env=env)
  544. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0]
  545. def generate_cpp_hint_file(filename):
  546. if os.path.isfile(filename):
  547. # Don't overwrite an existing hint file since the user may have customized it.
  548. pass
  549. else:
  550. try:
  551. with open(filename, "w", encoding="utf-8", newline="\n") as fd:
  552. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  553. for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]:
  554. for count in range(13):
  555. for suffix in ["", "R", "C", "RC"]:
  556. fd.write(f"#define {name}{count}{suffix}(")
  557. if "R" in suffix:
  558. fd.write("m_ret, ")
  559. fd.write("m_name")
  560. for idx in range(1, count + 1):
  561. fd.write(f", type{idx}")
  562. fd.write(")\n")
  563. except OSError:
  564. print_warning("Could not write cpp.hint file.")
  565. def glob_recursive(pattern, node="."):
  566. from SCons import Node
  567. from SCons.Script import Glob
  568. results = []
  569. for f in Glob(str(node) + "/*", source=True):
  570. if type(f) is Node.FS.Dir:
  571. results += glob_recursive(pattern, f)
  572. results += Glob(str(node) + "/" + pattern, source=True)
  573. return results
  574. def add_to_vs_project(env, sources):
  575. for x in sources:
  576. fname = env.File(x).path if isinstance(x, str) else env.File(x)[0].path
  577. pieces = fname.split(".")
  578. if len(pieces) > 0:
  579. basename = pieces[0]
  580. basename = basename.replace("\\\\", "/")
  581. if os.path.isfile(basename + ".h"):
  582. env.vs_incs += [basename + ".h"]
  583. elif os.path.isfile(basename + ".hpp"):
  584. env.vs_incs += [basename + ".hpp"]
  585. if os.path.isfile(basename + ".c"):
  586. env.vs_srcs += [basename + ".c"]
  587. elif os.path.isfile(basename + ".cpp"):
  588. env.vs_srcs += [basename + ".cpp"]
  589. def precious_program(env, program, sources, **args):
  590. program = env.ProgramOriginal(program, sources, **args)
  591. env.Precious(program)
  592. return program
  593. def add_shared_library(env, name, sources, **args):
  594. library = env.SharedLibrary(name, sources, **args)
  595. env.NoCache(library)
  596. return library
  597. def add_library(env, name, sources, **args):
  598. library = env.Library(name, sources, **args)
  599. env.NoCache(library)
  600. return library
  601. def add_program(env, name, sources, **args):
  602. program = env.Program(name, sources, **args)
  603. env.NoCache(program)
  604. return program
  605. def CommandNoCache(env, target, sources, command, **args):
  606. result = env.Command(target, sources, command, **args)
  607. env.NoCache(result)
  608. return result
  609. def Run(env, function):
  610. from SCons.Script import Action
  611. return Action(function, "$GENCOMSTR")
  612. def detect_darwin_sdk_path(platform, env):
  613. sdk_name = ""
  614. if platform == "macos":
  615. sdk_name = "macosx"
  616. var_name = "MACOS_SDK_PATH"
  617. elif platform == "ios":
  618. sdk_name = "iphoneos"
  619. var_name = "IOS_SDK_PATH"
  620. elif platform == "iossimulator":
  621. sdk_name = "iphonesimulator"
  622. var_name = "IOS_SDK_PATH"
  623. else:
  624. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  625. if not env[var_name]:
  626. try:
  627. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  628. if sdk_path:
  629. env[var_name] = sdk_path
  630. except (subprocess.CalledProcessError, OSError):
  631. print_error("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  632. raise
  633. def is_vanilla_clang(env):
  634. if not using_clang(env):
  635. return False
  636. try:
  637. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  638. except (subprocess.CalledProcessError, OSError):
  639. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  640. return False
  641. return not version.startswith("Apple")
  642. def get_compiler_version(env):
  643. """
  644. Returns a dictionary with various version information:
  645. - major, minor, patch: Version following semantic versioning system
  646. - metadata1, metadata2: Extra information
  647. - date: Date of the build
  648. """
  649. ret = {
  650. "major": -1,
  651. "minor": -1,
  652. "patch": -1,
  653. "metadata1": "",
  654. "metadata2": "",
  655. "date": "",
  656. "apple_major": -1,
  657. "apple_minor": -1,
  658. "apple_patch1": -1,
  659. "apple_patch2": -1,
  660. "apple_patch3": -1,
  661. }
  662. if env.msvc and not using_clang(env):
  663. try:
  664. # FIXME: `-latest` works for most cases, but there are edge-cases where this would
  665. # benefit from a more nuanced search.
  666. # https://github.com/godotengine/godot/pull/91069#issuecomment-2358956731
  667. # https://github.com/godotengine/godot/pull/91069#issuecomment-2380836341
  668. args = [
  669. env["VSWHERE"],
  670. "-latest",
  671. "-prerelease",
  672. "-products",
  673. "*",
  674. "-requires",
  675. "Microsoft.Component.MSBuild",
  676. "-utf8",
  677. ]
  678. version = subprocess.check_output(args, encoding="utf-8").strip()
  679. for line in version.splitlines():
  680. split = line.split(":", 1)
  681. if split[0] == "catalog_productDisplayVersion":
  682. sem_ver = split[1].split(".")
  683. ret["major"] = int(sem_ver[0])
  684. ret["minor"] = int(sem_ver[1])
  685. ret["patch"] = int(sem_ver[2].split()[0])
  686. # Could potentially add section for determining preview version, but
  687. # that can wait until metadata is actually used for something.
  688. if split[0] == "catalog_buildVersion":
  689. ret["metadata1"] = split[1]
  690. except (subprocess.CalledProcessError, OSError):
  691. print_warning("Couldn't find vswhere to determine compiler version.")
  692. return ret
  693. # Not using -dumpversion as some GCC distros only return major, and
  694. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  695. try:
  696. version = subprocess.check_output(
  697. [env.subst(env["CXX"]), "--version"], shell=(os.name == "nt"), encoding="utf-8"
  698. ).strip()
  699. except (subprocess.CalledProcessError, OSError):
  700. print_warning("Couldn't parse CXX environment variable to infer compiler version.")
  701. return ret
  702. match = re.search(
  703. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  704. r"(?P<major>\d+)"
  705. r"(?:\.(?P<minor>\d*))?"
  706. r"(?:\.(?P<patch>\d*))?"
  707. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  708. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  709. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  710. version,
  711. )
  712. if match is not None:
  713. for key, value in match.groupdict().items():
  714. if value is not None:
  715. ret[key] = value
  716. match_apple = re.search(
  717. r"(?:(?<=clang-)|(?<=\) )|(?<=^))"
  718. r"(?P<apple_major>\d+)"
  719. r"(?:\.(?P<apple_minor>\d*))?"
  720. r"(?:\.(?P<apple_patch1>\d*))?"
  721. r"(?:\.(?P<apple_patch2>\d*))?"
  722. r"(?:\.(?P<apple_patch3>\d*))?",
  723. version,
  724. )
  725. if match_apple is not None:
  726. for key, value in match_apple.groupdict().items():
  727. if value is not None:
  728. ret[key] = value
  729. # Transform semantic versioning to integers
  730. for key in [
  731. "major",
  732. "minor",
  733. "patch",
  734. "apple_major",
  735. "apple_minor",
  736. "apple_patch1",
  737. "apple_patch2",
  738. "apple_patch3",
  739. ]:
  740. ret[key] = int(ret[key] or -1)
  741. return ret
  742. def using_gcc(env):
  743. return "gcc" in os.path.basename(env["CC"])
  744. def using_clang(env):
  745. return "clang" in os.path.basename(env["CC"])
  746. def using_emcc(env):
  747. return "emcc" in os.path.basename(env["CC"])
  748. def show_progress(env):
  749. if env["ninja"]:
  750. # Has its own progress/tracking tool that clashes with ours
  751. return
  752. import sys
  753. from SCons.Script import AlwaysBuild, Command, Progress
  754. screen = sys.stdout
  755. # Progress reporting is not available in non-TTY environments since it
  756. # messes with the output (for example, when writing to a file)
  757. show_progress = env["progress"] and sys.stdout.isatty()
  758. node_count = 0
  759. node_count_max = 0
  760. node_count_interval = 1
  761. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  762. import math
  763. class cache_progress:
  764. # The default is 1 GB cache
  765. def __init__(self, path=None, limit=pow(1024, 3)):
  766. self.path = path
  767. self.limit = limit
  768. if env["verbose"] and path is not None:
  769. screen.write(
  770. "Current cache limit is {} (used: {})\n".format(
  771. self.convert_size(limit), self.convert_size(self.get_size(path))
  772. )
  773. )
  774. def __call__(self, node, *args, **kw):
  775. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  776. if show_progress:
  777. # Print the progress percentage
  778. node_count += node_count_interval
  779. if node_count_max > 0 and node_count <= node_count_max:
  780. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  781. screen.flush()
  782. elif node_count_max > 0 and node_count > node_count_max:
  783. screen.write("\r[100%] ")
  784. screen.flush()
  785. else:
  786. screen.write("\r[Initial build] ")
  787. screen.flush()
  788. def convert_size(self, size_bytes):
  789. if size_bytes == 0:
  790. return "0 bytes"
  791. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  792. i = int(math.floor(math.log(size_bytes, 1024)))
  793. p = math.pow(1024, i)
  794. s = round(size_bytes / p, 2)
  795. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  796. def get_size(self, start_path="."):
  797. total_size = 0
  798. for dirpath, dirnames, filenames in os.walk(start_path):
  799. for f in filenames:
  800. fp = os.path.join(dirpath, f)
  801. total_size += os.path.getsize(fp)
  802. return total_size
  803. def progress_finish(target, source, env):
  804. nonlocal node_count, progressor
  805. try:
  806. with open(node_count_fname, "w", encoding="utf-8", newline="\n") as f:
  807. f.write("%d\n" % node_count)
  808. except Exception:
  809. pass
  810. try:
  811. with open(node_count_fname, "r", encoding="utf-8") as f:
  812. node_count_max = int(f.readline())
  813. except Exception:
  814. pass
  815. cache_directory = os.environ.get("SCONS_CACHE")
  816. # Simple cache pruning, attached to SCons' progress callback. Trim the
  817. # cache directory to a size not larger than cache_limit.
  818. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  819. progressor = cache_progress(cache_directory, cache_limit)
  820. Progress(progressor, interval=node_count_interval)
  821. progress_finish_command = Command("progress_finish", [], progress_finish)
  822. AlwaysBuild(progress_finish_command)
  823. def clean_cache(env):
  824. import atexit
  825. import time
  826. class cache_clean:
  827. def __init__(self, path=None, limit=pow(1024, 3)):
  828. self.path = path
  829. self.limit = limit
  830. def clean(self):
  831. self.delete(self.file_list())
  832. def delete(self, files):
  833. if len(files) == 0:
  834. return
  835. if env["verbose"]:
  836. # Utter something
  837. print("Purging %d %s from cache..." % (len(files), "files" if len(files) > 1 else "file"))
  838. [os.remove(f) for f in files]
  839. def file_list(self):
  840. if self.path is None:
  841. # Nothing to do
  842. return []
  843. # Gather a list of (filename, (size, atime)) within the
  844. # cache directory
  845. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  846. if file_stat == []:
  847. # Nothing to do
  848. return []
  849. # Weight the cache files by size (assumed to be roughly
  850. # proportional to the recompilation time) times an exponential
  851. # decay since the ctime, and return a list with the entries
  852. # (filename, size, weight).
  853. current_time = time.time()
  854. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  855. # Sort by the most recently accessed files (most sensible to keep) first
  856. file_stat.sort(key=lambda x: x[2])
  857. # Search for the first entry where the storage limit is
  858. # reached
  859. sum, mark = 0, None
  860. for i, x in enumerate(file_stat):
  861. sum += x[1]
  862. if sum > self.limit:
  863. mark = i
  864. break
  865. if mark is None:
  866. return []
  867. else:
  868. return [x[0] for x in file_stat[mark:]]
  869. def cache_finally():
  870. nonlocal cleaner
  871. try:
  872. cleaner.clean()
  873. except Exception:
  874. pass
  875. cache_directory = os.environ.get("SCONS_CACHE")
  876. # Simple cache pruning, attached to SCons' progress callback. Trim the
  877. # cache directory to a size not larger than cache_limit.
  878. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  879. cleaner = cache_clean(cache_directory, cache_limit)
  880. atexit.register(cache_finally)
  881. def dump(env):
  882. # Dumps latest build information for debugging purposes and external tools.
  883. from json import dump
  884. def non_serializable(obj):
  885. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  886. with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as f:
  887. dump(env.Dictionary(), f, indent=4, default=non_serializable)
  888. # Custom Visual Studio project generation logic that supports any platform that has a msvs.py
  889. # script, so Visual Studio can be used to run scons for any platform, with the right defines per target.
  890. # Invoked with scons vsproj=yes
  891. #
  892. # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included.
  893. # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch
  894. # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are
  895. # on the active build target.
  896. #
  897. # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build,
  898. # but will have the files and configuration for the windows editor target.
  899. #
  900. # To generate build configuration files for all platforms+targets+arch combinations, users can call
  901. # scons vsproj=yes
  902. # for each combination of platform+target+arch. This will generate the relevant vs project files but
  903. # skip the build process. This lets project files be quickly generated even if there are build errors.
  904. #
  905. # To generate AND build from the command line:
  906. # scons vsproj=yes vsproj_gen_only=no
  907. def generate_vs_project(env, original_args, project_name="godot"):
  908. # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content.
  909. def glob_recursive_2(pattern, dirs, node="."):
  910. from SCons import Node
  911. from SCons.Script import Glob
  912. results = []
  913. for f in Glob(str(node) + "/*", source=True):
  914. if type(f) is Node.FS.Dir:
  915. results += glob_recursive_2(pattern, dirs, f)
  916. r = Glob(str(node) + "/" + pattern, source=True)
  917. if len(r) > 0 and str(node) not in dirs:
  918. d = ""
  919. for part in str(node).split("\\"):
  920. d += part
  921. if d not in dirs:
  922. dirs.append(d)
  923. d += "\\"
  924. results += r
  925. return results
  926. def get_bool(args, option, default):
  927. from SCons.Variables.BoolVariable import _text2bool
  928. val = args.get(option, default)
  929. if val is not None:
  930. try:
  931. return _text2bool(val)
  932. except (ValueError, AttributeError):
  933. return default
  934. else:
  935. return default
  936. def format_key_value(v):
  937. if type(v) in [tuple, list]:
  938. return v[0] if len(v) == 1 else f"{v[0]}={v[1]}"
  939. return v
  940. filtered_args = original_args.copy()
  941. # Ignore the "vsproj" option to not regenerate the VS project on every build
  942. filtered_args.pop("vsproj", None)
  943. # This flag allows users to regenerate the proj files but skip the building process.
  944. # This lets projects be regenerated even if there are build errors.
  945. filtered_args.pop("vsproj_gen_only", None)
  946. # This flag allows users to regenerate only the props file without touching the sln or vcxproj files.
  947. # This preserves any customizations users have done to the solution, while still updating the file list
  948. # and build commands.
  949. filtered_args.pop("vsproj_props_only", None)
  950. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  951. filtered_args.pop("progress", None)
  952. # We add these three manually because they might not be explicitly passed in, and it's important to always set them.
  953. filtered_args.pop("platform", None)
  954. filtered_args.pop("target", None)
  955. filtered_args.pop("arch", None)
  956. platform = env["platform"]
  957. target = env["target"]
  958. arch = env["arch"]
  959. vs_configuration = {}
  960. common_build_prefix = []
  961. confs = []
  962. for x in sorted(glob.glob("platform/*")):
  963. # Only platforms that opt in to vs proj generation are included.
  964. if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"):
  965. continue
  966. tmppath = "./" + x
  967. sys.path.insert(0, tmppath)
  968. import msvs
  969. vs_plats = []
  970. vs_confs = []
  971. try:
  972. platform_name = x[9:]
  973. vs_plats = msvs.get_platforms()
  974. vs_confs = msvs.get_configurations()
  975. val = []
  976. for plat in vs_plats:
  977. val += [{"platform": plat[0], "architecture": plat[1]}]
  978. vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val}
  979. confs += [vsconf]
  980. # Save additional information about the configuration for the actively selected platform,
  981. # so we can generate the platform-specific props file with all the build commands/defines/etc
  982. if platform == platform_name:
  983. common_build_prefix = msvs.get_build_prefix(env)
  984. vs_configuration = vsconf
  985. except Exception:
  986. pass
  987. sys.path.remove(tmppath)
  988. sys.modules.pop("msvs")
  989. headers = []
  990. headers_dirs = []
  991. for file in glob_recursive_2("*.h", headers_dirs):
  992. headers.append(str(file).replace("/", "\\"))
  993. for file in glob_recursive_2("*.hpp", headers_dirs):
  994. headers.append(str(file).replace("/", "\\"))
  995. sources = []
  996. sources_dirs = []
  997. for file in glob_recursive_2("*.cpp", sources_dirs):
  998. sources.append(str(file).replace("/", "\\"))
  999. for file in glob_recursive_2("*.c", sources_dirs):
  1000. sources.append(str(file).replace("/", "\\"))
  1001. others = []
  1002. others_dirs = []
  1003. for file in glob_recursive_2("*.natvis", others_dirs):
  1004. others.append(str(file).replace("/", "\\"))
  1005. for file in glob_recursive_2("*.glsl", others_dirs):
  1006. others.append(str(file).replace("/", "\\"))
  1007. skip_filters = False
  1008. import hashlib
  1009. import json
  1010. md5 = hashlib.md5(
  1011. json.dumps(headers + headers_dirs + sources + sources_dirs + others + others_dirs, sort_keys=True).encode(
  1012. "utf-8"
  1013. )
  1014. ).hexdigest()
  1015. if os.path.exists(f"{project_name}.vcxproj.filters"):
  1016. with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file:
  1017. existing_filters = file.read()
  1018. match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters)
  1019. if match is not None and md5 == match.group(1):
  1020. skip_filters = True
  1021. import uuid
  1022. # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs.
  1023. if not skip_filters:
  1024. print(f"Regenerating {project_name}.vcxproj.filters")
  1025. with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file:
  1026. filters_template = file.read()
  1027. for i in range(1, 10):
  1028. filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4()))
  1029. filters = ""
  1030. for d in headers_dirs:
  1031. filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1032. for d in sources_dirs:
  1033. filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1034. for d in others_dirs:
  1035. filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n'
  1036. filters_template = filters_template.replace("%%FILTERS%%", filters)
  1037. filters = ""
  1038. for file in headers:
  1039. filters += (
  1040. f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n'
  1041. )
  1042. filters_template = filters_template.replace("%%INCLUDES%%", filters)
  1043. filters = ""
  1044. for file in sources:
  1045. filters += (
  1046. f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n'
  1047. )
  1048. filters_template = filters_template.replace("%%COMPILES%%", filters)
  1049. filters = ""
  1050. for file in others:
  1051. filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n'
  1052. filters_template = filters_template.replace("%%OTHERS%%", filters)
  1053. filters_template = filters_template.replace("%%HASH%%", md5)
  1054. with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f:
  1055. f.write(filters_template)
  1056. envsources = []
  1057. envsources += env.core_sources
  1058. envsources += env.drivers_sources
  1059. envsources += env.main_sources
  1060. envsources += env.modules_sources
  1061. envsources += env.scene_sources
  1062. envsources += env.servers_sources
  1063. if env.editor_build:
  1064. envsources += env.editor_sources
  1065. envsources += env.platform_sources
  1066. headers_active = []
  1067. sources_active = []
  1068. others_active = []
  1069. for x in envsources:
  1070. fname = ""
  1071. if isinstance(x, str):
  1072. fname = env.File(x).path
  1073. else:
  1074. # Some object files might get added directly as a File object and not a list.
  1075. try:
  1076. fname = env.File(x)[0].path
  1077. except Exception:
  1078. fname = x.path
  1079. pass
  1080. if fname:
  1081. fname = fname.replace("\\\\", "/")
  1082. parts = os.path.splitext(fname)
  1083. basename = parts[0]
  1084. ext = parts[1]
  1085. idx = fname.find(env["OBJSUFFIX"])
  1086. if ext in [".h", ".hpp"]:
  1087. headers_active += [fname]
  1088. elif ext in [".c", ".cpp"]:
  1089. sources_active += [fname]
  1090. elif idx > 0:
  1091. basename = fname[:idx]
  1092. if os.path.isfile(basename + ".h"):
  1093. headers_active += [basename + ".h"]
  1094. elif os.path.isfile(basename + ".hpp"):
  1095. headers_active += [basename + ".hpp"]
  1096. elif basename.endswith(".gen") and os.path.isfile(basename[:-4] + ".h"):
  1097. headers_active += [basename[:-4] + ".h"]
  1098. if os.path.isfile(basename + ".c"):
  1099. sources_active += [basename + ".c"]
  1100. elif os.path.isfile(basename + ".cpp"):
  1101. sources_active += [basename + ".cpp"]
  1102. else:
  1103. fname = os.path.relpath(os.path.abspath(fname), env.Dir("").abspath)
  1104. others_active += [fname]
  1105. all_items = []
  1106. properties = []
  1107. activeItems = []
  1108. extraItems = []
  1109. set_headers = set(headers_active)
  1110. set_sources = set(sources_active)
  1111. set_others = set(others_active)
  1112. for file in headers:
  1113. base_path = os.path.dirname(file).replace("\\", "_")
  1114. all_items.append(f'<ClInclude Include="{file}">')
  1115. all_items.append(
  1116. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1117. )
  1118. all_items.append("</ClInclude>")
  1119. if file in set_headers:
  1120. activeItems.append(file)
  1121. for file in sources:
  1122. base_path = os.path.dirname(file).replace("\\", "_")
  1123. all_items.append(f'<ClCompile Include="{file}">')
  1124. all_items.append(
  1125. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1126. )
  1127. all_items.append("</ClCompile>")
  1128. if file in set_sources:
  1129. activeItems.append(file)
  1130. for file in others:
  1131. base_path = os.path.dirname(file).replace("\\", "_")
  1132. all_items.append(f'<None Include="{file}">')
  1133. all_items.append(
  1134. f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>"
  1135. )
  1136. all_items.append("</None>")
  1137. if file in set_others:
  1138. activeItems.append(file)
  1139. if vs_configuration:
  1140. vsconf = ""
  1141. for a in vs_configuration["arches"]:
  1142. if arch == a["architecture"]:
  1143. vsconf = f'{target}|{a["platform"]}'
  1144. break
  1145. condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'"
  1146. itemlist = {}
  1147. for item in activeItems:
  1148. key = os.path.dirname(item).replace("\\", "_")
  1149. if key not in itemlist:
  1150. itemlist[key] = [item]
  1151. else:
  1152. itemlist[key] += [item]
  1153. for x in itemlist.keys():
  1154. properties.append(
  1155. "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
  1156. )
  1157. output = f'bin\\godot{env["PROGSUFFIX"]}'
  1158. with open("misc/msvs/props.template", "r", encoding="utf-8") as file:
  1159. props_template = file.read()
  1160. props_template = props_template.replace("%%VSCONF%%", vsconf)
  1161. props_template = props_template.replace("%%CONDITION%%", condition)
  1162. props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1163. props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems))
  1164. props_template = props_template.replace("%%OUTPUT%%", output)
  1165. proplist = [format_key_value(v) for v in list(env["CPPDEFINES"])]
  1166. proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])]
  1167. props_template = props_template.replace("%%DEFINES%%", ";".join(proplist))
  1168. proplist = [str(j) for j in env["CPPPATH"]]
  1169. proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])]
  1170. props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist))
  1171. proplist = env["CCFLAGS"]
  1172. proplist += [x for x in env["CXXFLAGS"] if not x.startswith("$")]
  1173. proplist += [str(j) for j in env.get("VSHINT_OPTIONS", [])]
  1174. props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist))
  1175. # Windows allows us to have spaces in paths, so we need
  1176. # to double quote off the directory. However, the path ends
  1177. # in a backslash, so we need to remove this, lest it escape the
  1178. # last double quote off, confusing MSBuild
  1179. common_build_postfix = [
  1180. "--directory=&quot;$(ProjectDir.TrimEnd(&apos;\\&apos;))&quot;",
  1181. "progress=no",
  1182. f"platform={platform}",
  1183. f"target={target}",
  1184. f"arch={arch}",
  1185. ]
  1186. for arg, value in filtered_args.items():
  1187. common_build_postfix.append(f"{arg}={value}")
  1188. cmd_rebuild = [
  1189. "vsproj=yes",
  1190. "vsproj_props_only=yes",
  1191. "vsproj_gen_only=no",
  1192. f"vsproj_name={project_name}",
  1193. ] + common_build_postfix
  1194. cmd_clean = [
  1195. "--clean",
  1196. ] + common_build_postfix
  1197. commands = "scons"
  1198. if len(common_build_prefix) == 0:
  1199. commands = "echo Starting SCons &amp;&amp; cmd /V /C " + commands
  1200. else:
  1201. common_build_prefix[0] = "echo Starting SCons &amp;&amp; cmd /V /C " + common_build_prefix[0]
  1202. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  1203. props_template = props_template.replace("%%BUILD%%", cmd)
  1204. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)])
  1205. props_template = props_template.replace("%%REBUILD%%", cmd)
  1206. cmd = " ^&amp; ".join(common_build_prefix + [" ".join([commands] + cmd_clean)])
  1207. props_template = props_template.replace("%%CLEAN%%", cmd)
  1208. with open(
  1209. f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n"
  1210. ) as f:
  1211. f.write(props_template)
  1212. proj_uuid = str(uuid.uuid4())
  1213. sln_uuid = str(uuid.uuid4())
  1214. if os.path.exists(f"{project_name}.sln"):
  1215. for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines():
  1216. if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'):
  1217. proj_uuid = re.search(
  1218. 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)}\"$",
  1219. line,
  1220. ).group(1)
  1221. elif line.strip().startswith("SolutionGuid ="):
  1222. sln_uuid = re.search(
  1223. 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
  1224. ).group(1)
  1225. break
  1226. configurations = []
  1227. imports = []
  1228. properties = []
  1229. section1 = []
  1230. section2 = []
  1231. for conf in confs:
  1232. godot_platform = conf["platform"]
  1233. for p in conf["arches"]:
  1234. sln_plat = p["platform"]
  1235. proj_plat = sln_plat
  1236. godot_arch = p["architecture"]
  1237. # Redirect editor configurations for non-Windows platforms to the Windows one, so the solution has all the permutations
  1238. # and VS doesn't complain about missing project configurations.
  1239. # These configurations are disabled, so they show up but won't build.
  1240. if godot_platform != "windows":
  1241. section1 += [f"editor|{sln_plat} = editor|{proj_plat}"]
  1242. section2 += [
  1243. f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{proj_plat}",
  1244. ]
  1245. for t in conf["targets"]:
  1246. godot_target = t
  1247. # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86.
  1248. if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32":
  1249. sln_plat = "x86"
  1250. configurations += [
  1251. f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">',
  1252. f" <Configuration>{godot_target}</Configuration>",
  1253. f" <Platform>{proj_plat}</Platform>",
  1254. "</ProjectConfiguration>",
  1255. ]
  1256. properties += [
  1257. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">",
  1258. f" <GodotConfiguration>{godot_target}</GodotConfiguration>",
  1259. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1260. "</PropertyGroup>",
  1261. ]
  1262. if godot_platform != "windows":
  1263. configurations += [
  1264. f'<ProjectConfiguration Include="editor|{proj_plat}">',
  1265. " <Configuration>editor</Configuration>",
  1266. f" <Platform>{proj_plat}</Platform>",
  1267. "</ProjectConfiguration>",
  1268. ]
  1269. properties += [
  1270. f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
  1271. " <GodotConfiguration>editor</GodotConfiguration>",
  1272. f" <GodotPlatform>{proj_plat}</GodotPlatform>",
  1273. "</PropertyGroup>",
  1274. ]
  1275. p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props"
  1276. imports += [
  1277. f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>'
  1278. ]
  1279. section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"]
  1280. section2 += [
  1281. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}",
  1282. f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}",
  1283. ]
  1284. # Add an extra import for a local user props file at the end, so users can add more overrides.
  1285. imports += [
  1286. f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>'
  1287. ]
  1288. section1 = sorted(section1)
  1289. section2 = sorted(section2)
  1290. if not get_bool(original_args, "vsproj_props_only", False):
  1291. with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file:
  1292. proj_template = file.read()
  1293. proj_template = proj_template.replace("%%UUID%%", proj_uuid)
  1294. proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations))
  1295. proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports))
  1296. proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items))
  1297. proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties))
  1298. with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f:
  1299. f.write(proj_template)
  1300. if not get_bool(original_args, "vsproj_props_only", False):
  1301. with open("misc/msvs/sln.template", "r", encoding="utf-8") as file:
  1302. sln_template = file.read()
  1303. sln_template = sln_template.replace("%%NAME%%", project_name)
  1304. sln_template = sln_template.replace("%%UUID%%", proj_uuid)
  1305. sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid)
  1306. sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1))
  1307. sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2))
  1308. with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f:
  1309. f.write(sln_template)
  1310. if get_bool(original_args, "vsproj_gen_only", True):
  1311. sys.exit()
  1312. def generate_copyright_header(filename: str) -> str:
  1313. MARGIN = 70
  1314. TEMPLATE = """\
  1315. /**************************************************************************/
  1316. /* %s*/
  1317. /**************************************************************************/
  1318. /* This file is part of: */
  1319. /* GODOT ENGINE */
  1320. /* https://godotengine.org */
  1321. /**************************************************************************/
  1322. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  1323. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  1324. /* */
  1325. /* Permission is hereby granted, free of charge, to any person obtaining */
  1326. /* a copy of this software and associated documentation files (the */
  1327. /* "Software"), to deal in the Software without restriction, including */
  1328. /* without limitation the rights to use, copy, modify, merge, publish, */
  1329. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1330. /* permit persons to whom the Software is furnished to do so, subject to */
  1331. /* the following conditions: */
  1332. /* */
  1333. /* The above copyright notice and this permission notice shall be */
  1334. /* included in all copies or substantial portions of the Software. */
  1335. /* */
  1336. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1337. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1338. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  1339. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1340. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1341. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1342. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1343. /**************************************************************************/
  1344. """
  1345. filename = filename.split("/")[-1].ljust(MARGIN)
  1346. if len(filename) > MARGIN:
  1347. print(f'WARNING: Filename "{filename}" too large for copyright header.')
  1348. return TEMPLATE % filename
  1349. @contextlib.contextmanager
  1350. def generated_wrapper(
  1351. path, # FIXME: type with `Union[str, Node, List[Node]]` when pytest conflicts are resolved
  1352. guard: Optional[bool] = None,
  1353. prefix: str = "",
  1354. suffix: str = "",
  1355. ) -> Generator[TextIOWrapper, None, None]:
  1356. """
  1357. Wrapper class to automatically handle copyright headers and header guards
  1358. for generated scripts. Meant to be invoked via `with` statement similar to
  1359. creating a file.
  1360. - `path`: The path of the file to be created. Can be passed a raw string, an
  1361. isolated SCons target, or a full SCons target list. If a target list contains
  1362. multiple entries, produces a warning & only creates the first entry.
  1363. - `guard`: Optional bool to determine if a header guard should be added. If
  1364. unassigned, header guards are determined by the file extension.
  1365. - `prefix`: Custom prefix to prepend to a header guard. Produces a warning if
  1366. provided a value when `guard` evaluates to `False`.
  1367. - `suffix`: Custom suffix to append to a header guard. Produces a warning if
  1368. provided a value when `guard` evaluates to `False`.
  1369. """
  1370. # Handle unfiltered SCons target[s] passed as path.
  1371. if not isinstance(path, str):
  1372. if isinstance(path, list):
  1373. if len(path) > 1:
  1374. print_warning(
  1375. "Attempting to use generated wrapper with multiple targets; "
  1376. f"will only use first entry: {path[0]}"
  1377. )
  1378. path = path[0]
  1379. if not hasattr(path, "get_abspath"):
  1380. raise TypeError(f'Expected type "str", "Node" or "List[Node]"; was passed {type(path)}.')
  1381. path = path.get_abspath()
  1382. path = str(path).replace("\\", "/")
  1383. if guard is None:
  1384. guard = path.endswith((".h", ".hh", ".hpp", ".inc"))
  1385. if not guard and (prefix or suffix):
  1386. print_warning(f'Trying to assign header guard prefix/suffix while `guard` is disabled: "{path}".')
  1387. header_guard = ""
  1388. if guard:
  1389. if prefix:
  1390. prefix += "_"
  1391. if suffix:
  1392. suffix = f"_{suffix}"
  1393. split = path.split("/")[-1].split(".")
  1394. header_guard = (f"{prefix}{split[0]}{suffix}.{'.'.join(split[1:])}".upper()
  1395. .replace(".", "_").replace("-", "_").replace(" ", "_").replace("__", "_")) # fmt: skip
  1396. with open(path, "wt", encoding="utf-8", newline="\n") as file:
  1397. file.write(generate_copyright_header(path))
  1398. file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n")
  1399. if guard:
  1400. file.write(f"#ifndef {header_guard}\n")
  1401. file.write(f"#define {header_guard}\n\n")
  1402. with StringIO(newline="\n") as str_io:
  1403. yield str_io
  1404. file.write(str_io.getvalue().strip() or "/* NO CONTENT */")
  1405. if guard:
  1406. file.write(f"\n\n#endif // {header_guard}")
  1407. file.write("\n")
  1408. def to_raw_cstring(value: Union[str, List[str]]) -> str:
  1409. MAX_LITERAL = 16 * 1024
  1410. if isinstance(value, list):
  1411. value = "\n".join(value) + "\n"
  1412. split: List[bytes] = []
  1413. offset = 0
  1414. encoded = value.encode()
  1415. while offset <= len(encoded):
  1416. segment = encoded[offset : offset + MAX_LITERAL]
  1417. offset += MAX_LITERAL
  1418. if len(segment) == MAX_LITERAL:
  1419. # Try to segment raw strings at double newlines to keep readable.
  1420. pretty_break = segment.rfind(b"\n\n")
  1421. if pretty_break != -1:
  1422. segment = segment[: pretty_break + 1]
  1423. offset -= MAX_LITERAL - pretty_break - 1
  1424. # If none found, ensure we end with valid utf8.
  1425. # https://github.com/halloleo/unicut/blob/master/truncate.py
  1426. elif segment[-1] & 0b10000000:
  1427. last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0]
  1428. last_11xxxxxx = segment[last_11xxxxxx_index]
  1429. if not last_11xxxxxx & 0b00100000:
  1430. last_char_length = 2
  1431. elif not last_11xxxxxx & 0b0010000:
  1432. last_char_length = 3
  1433. elif not last_11xxxxxx & 0b0001000:
  1434. last_char_length = 4
  1435. if last_char_length > -last_11xxxxxx_index:
  1436. segment = segment[:last_11xxxxxx_index]
  1437. offset += last_11xxxxxx_index
  1438. split += [segment]
  1439. return " ".join(f'R"<!>({x.decode()})<!>"' for x in split)