methods.py 67 KB

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