methods.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. import os
  2. import sys
  3. import re
  4. import glob
  5. import subprocess
  6. from collections import OrderedDict
  7. from collections.abc import Mapping
  8. from typing import Iterator
  9. from pathlib import Path
  10. from os.path import normpath, basename
  11. # Get the "Godot" folder name ahead of time
  12. base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/"
  13. base_folder_only = os.path.basename(os.path.normpath(base_folder_path))
  14. # Listing all the folders we have converted
  15. # for SCU in scu_builders.py
  16. _scu_folders = set()
  17. def set_scu_folders(scu_folders):
  18. global _scu_folders
  19. _scu_folders = scu_folders
  20. def add_source_files_orig(self, sources, files, allow_gen=False):
  21. # Convert string to list of absolute paths (including expanding wildcard)
  22. if isinstance(files, (str, bytes)):
  23. # Keep SCons project-absolute path as they are (no wildcard support)
  24. if files.startswith("#"):
  25. if "*" in files:
  26. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  27. return
  28. files = [files]
  29. else:
  30. # Exclude .gen.cpp files from globbing, to avoid including obsolete ones.
  31. # They should instead be added manually.
  32. skip_gen_cpp = "*" in files
  33. dir_path = self.Dir(".").abspath
  34. files = sorted(glob.glob(dir_path + "/" + files))
  35. if skip_gen_cpp and not allow_gen:
  36. files = [f for f in files if not f.endswith(".gen.cpp")]
  37. # Add each path as compiled Object following environment (self) configuration
  38. for path in files:
  39. obj = self.Object(path)
  40. if obj in sources:
  41. print('WARNING: Object "{}" already included in environment sources.'.format(obj))
  42. continue
  43. sources.append(obj)
  44. # The section name is used for checking
  45. # the hash table to see whether the folder
  46. # is included in the SCU build.
  47. # It will be something like "core/math".
  48. def _find_scu_section_name(subdir):
  49. section_path = os.path.abspath(subdir) + "/"
  50. folders = []
  51. folder = ""
  52. for i in range(8):
  53. folder = os.path.dirname(section_path)
  54. folder = os.path.basename(folder)
  55. if folder == base_folder_only:
  56. break
  57. folders += [folder]
  58. section_path += "../"
  59. section_path = os.path.abspath(section_path) + "/"
  60. section_name = ""
  61. for n in range(len(folders)):
  62. # section_name += folders[len(folders) - n - 1] + " "
  63. section_name += folders[len(folders) - n - 1]
  64. if n != (len(folders) - 1):
  65. section_name += "/"
  66. return section_name
  67. def add_source_files_scu(self, sources, files, allow_gen=False):
  68. if self["scu_build"] and isinstance(files, str):
  69. if "*." not in files:
  70. return False
  71. # If the files are in a subdirectory, we want to create the scu gen
  72. # files inside this subdirectory.
  73. subdir = os.path.dirname(files)
  74. if subdir != "":
  75. subdir += "/"
  76. section_name = _find_scu_section_name(subdir)
  77. # if the section name is in the hash table?
  78. # i.e. is it part of the SCU build?
  79. global _scu_folders
  80. if section_name not in (_scu_folders):
  81. return False
  82. if self["verbose"]:
  83. print("SCU building " + section_name)
  84. # Add all the gen.cpp files in the SCU directory
  85. add_source_files_orig(self, sources, subdir + "scu/scu_*.gen.cpp", True)
  86. return True
  87. return False
  88. # Either builds the folder using the SCU system,
  89. # or reverts to regular build.
  90. def add_source_files(self, sources, files, allow_gen=False):
  91. if not add_source_files_scu(self, sources, files, allow_gen):
  92. # Wraps the original function when scu build is not active.
  93. add_source_files_orig(self, sources, files, allow_gen)
  94. return False
  95. return True
  96. def disable_warnings(self):
  97. # 'self' is the environment
  98. if self.msvc:
  99. # We have to remove existing warning level defines before appending /w,
  100. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  101. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  102. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  103. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  104. self.AppendUnique(CCFLAGS=["/w"])
  105. else:
  106. self.AppendUnique(CCFLAGS=["-w"])
  107. def force_optimization_on_debug(self):
  108. # 'self' is the environment
  109. if self["target"] == "template_release":
  110. return
  111. if self.msvc:
  112. # We have to remove existing optimization level defines before appending /O2,
  113. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  114. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  115. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  116. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  117. self.AppendUnique(CCFLAGS=["/O2"])
  118. else:
  119. self.AppendUnique(CCFLAGS=["-O3"])
  120. def add_module_version_string(self, s):
  121. self.module_version_string += "." + s
  122. def get_version_info(module_version_string="", silent=False):
  123. build_name = "custom_build"
  124. if os.getenv("BUILD_NAME") != None:
  125. build_name = str(os.getenv("BUILD_NAME"))
  126. if not silent:
  127. print(f"Using custom build name: '{build_name}'.")
  128. import version
  129. version_info = {
  130. "short_name": str(version.short_name),
  131. "name": str(version.name),
  132. "major": int(version.major),
  133. "minor": int(version.minor),
  134. "patch": int(version.patch),
  135. "status": str(version.status),
  136. "build": str(build_name),
  137. "module_config": str(version.module_config) + module_version_string,
  138. "year": int(version.year),
  139. "website": str(version.website),
  140. "docs_branch": str(version.docs),
  141. }
  142. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  143. # so this define provides a way to override it without having to modify the source.
  144. if os.getenv("GODOT_VERSION_STATUS") != None:
  145. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  146. if not silent:
  147. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  148. # Parse Git hash if we're in a Git repo.
  149. githash = ""
  150. gitfolder = ".git"
  151. if os.path.isfile(".git"):
  152. module_folder = open(".git", "r").readline().strip()
  153. if module_folder.startswith("gitdir: "):
  154. gitfolder = module_folder[8:]
  155. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  156. head = open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8").readline().strip()
  157. if head.startswith("ref: "):
  158. ref = head[5:]
  159. # If this directory is a Git worktree instead of a root clone.
  160. parts = gitfolder.split("/")
  161. if len(parts) > 2 and parts[-2] == "worktrees":
  162. gitfolder = "/".join(parts[0:-2])
  163. head = os.path.join(gitfolder, ref)
  164. packedrefs = os.path.join(gitfolder, "packed-refs")
  165. if os.path.isfile(head):
  166. githash = open(head, "r").readline().strip()
  167. elif os.path.isfile(packedrefs):
  168. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  169. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  170. for line in open(packedrefs, "r").read().splitlines():
  171. if line.startswith("#"):
  172. continue
  173. (line_hash, line_ref) = line.split(" ")
  174. if ref == line_ref:
  175. githash = line_hash
  176. break
  177. else:
  178. githash = head
  179. version_info["git_hash"] = githash
  180. return version_info
  181. def generate_version_header(module_version_string=""):
  182. version_info = get_version_info(module_version_string)
  183. # NOTE: It is safe to generate these files here, since this is still executed serially.
  184. f = open("core/version_generated.gen.h", "w")
  185. f.write(
  186. """/* THIS FILE IS GENERATED DO NOT EDIT */
  187. #ifndef VERSION_GENERATED_GEN_H
  188. #define VERSION_GENERATED_GEN_H
  189. #define VERSION_SHORT_NAME "{short_name}"
  190. #define VERSION_NAME "{name}"
  191. #define VERSION_MAJOR {major}
  192. #define VERSION_MINOR {minor}
  193. #define VERSION_PATCH {patch}
  194. #define VERSION_STATUS "{status}"
  195. #define VERSION_BUILD "{build}"
  196. #define VERSION_MODULE_CONFIG "{module_config}"
  197. #define VERSION_YEAR {year}
  198. #define VERSION_WEBSITE "{website}"
  199. #define VERSION_DOCS_BRANCH "{docs_branch}"
  200. #define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH
  201. #endif // VERSION_GENERATED_GEN_H
  202. """.format(
  203. **version_info
  204. )
  205. )
  206. f.close()
  207. fhash = open("core/version_hash.gen.cpp", "w")
  208. fhash.write(
  209. """/* THIS FILE IS GENERATED DO NOT EDIT */
  210. #include "core/version.h"
  211. const char *const VERSION_HASH = "{git_hash}";
  212. """.format(
  213. **version_info
  214. )
  215. )
  216. fhash.close()
  217. def parse_cg_file(fname, uniforms, sizes, conditionals):
  218. fs = open(fname, "r")
  219. line = fs.readline()
  220. while line:
  221. if re.match(r"^\s*uniform", line):
  222. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  223. type = res.groups(1)
  224. name = res.groups(2)
  225. uniforms.append(name)
  226. if type.find("texobj") != -1:
  227. sizes.append(1)
  228. else:
  229. t = re.match(r"float(\d)x(\d)", type)
  230. if t:
  231. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  232. else:
  233. t = re.match(r"float(\d)", type)
  234. sizes.append(int(t.groups(1)))
  235. if line.find("[branch]") != -1:
  236. conditionals.append(name)
  237. line = fs.readline()
  238. fs.close()
  239. def get_cmdline_bool(option, default):
  240. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  241. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  242. """
  243. from SCons.Script import ARGUMENTS
  244. from SCons.Variables.BoolVariable import _text2bool
  245. cmdline_val = ARGUMENTS.get(option)
  246. if cmdline_val is not None:
  247. return _text2bool(cmdline_val)
  248. else:
  249. return default
  250. def detect_modules(search_path, recursive=False):
  251. """Detects and collects a list of C++ modules at specified path
  252. `search_path` - a directory path containing modules. The path may point to
  253. a single module, which may have other nested modules. A module must have
  254. "register_types.h", "SCsub", "config.py" files created to be detected.
  255. `recursive` - if `True`, then all subdirectories are searched for modules as
  256. specified by the `search_path`, otherwise collects all modules under the
  257. `search_path` directory. If the `search_path` is a module, it is collected
  258. in all cases.
  259. Returns an `OrderedDict` with module names as keys, and directory paths as
  260. values. If a path is relative, then it is a built-in module. If a path is
  261. absolute, then it is a custom module collected outside of the engine source.
  262. """
  263. modules = OrderedDict()
  264. def add_module(path):
  265. module_name = os.path.basename(path)
  266. module_path = path.replace("\\", "/") # win32
  267. modules[module_name] = module_path
  268. def is_engine(path):
  269. # Prevent recursively detecting modules in self and other
  270. # Godot sources when using `custom_modules` build option.
  271. version_path = os.path.join(path, "version.py")
  272. if os.path.exists(version_path):
  273. with open(version_path) as f:
  274. if 'short_name = "godot"' in f.read():
  275. return True
  276. return False
  277. def get_files(path):
  278. files = glob.glob(os.path.join(path, "*"))
  279. # Sort so that `register_module_types` does not change that often,
  280. # and plugins are registered in alphabetic order as well.
  281. files.sort()
  282. return files
  283. if not recursive:
  284. if is_module(search_path):
  285. add_module(search_path)
  286. for path in get_files(search_path):
  287. if is_engine(path):
  288. continue
  289. if is_module(path):
  290. add_module(path)
  291. else:
  292. to_search = [search_path]
  293. while to_search:
  294. path = to_search.pop()
  295. if is_module(path):
  296. add_module(path)
  297. for child in get_files(path):
  298. if not os.path.isdir(child):
  299. continue
  300. if is_engine(child):
  301. continue
  302. to_search.insert(0, child)
  303. return modules
  304. def is_module(path):
  305. if not os.path.isdir(path):
  306. return False
  307. must_exist = ["register_types.h", "SCsub", "config.py"]
  308. for f in must_exist:
  309. if not os.path.exists(os.path.join(path, f)):
  310. return False
  311. return True
  312. def write_disabled_classes(class_list):
  313. f = open("core/disabled_classes.gen.h", "w")
  314. f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  315. f.write("#ifndef DISABLED_CLASSES_GEN_H\n")
  316. f.write("#define DISABLED_CLASSES_GEN_H\n\n")
  317. for c in class_list:
  318. cs = c.strip()
  319. if cs != "":
  320. f.write("#define ClassDB_Disable_" + cs + " 1\n")
  321. f.write("\n#endif\n")
  322. def write_modules(modules):
  323. includes_cpp = ""
  324. initialize_cpp = ""
  325. uninitialize_cpp = ""
  326. for name, path in modules.items():
  327. try:
  328. with open(os.path.join(path, "register_types.h")):
  329. includes_cpp += '#include "' + path + '/register_types.h"\n'
  330. initialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  331. initialize_cpp += "\tinitialize_" + name + "_module(p_level);\n"
  332. initialize_cpp += "#endif\n"
  333. uninitialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  334. uninitialize_cpp += "\tuninitialize_" + name + "_module(p_level);\n"
  335. uninitialize_cpp += "#endif\n"
  336. except OSError:
  337. pass
  338. modules_cpp = """// register_module_types.gen.cpp
  339. /* THIS FILE IS GENERATED DO NOT EDIT */
  340. #include "register_module_types.h"
  341. #include "modules/modules_enabled.gen.h"
  342. %s
  343. void initialize_modules(ModuleInitializationLevel p_level) {
  344. %s
  345. }
  346. void uninitialize_modules(ModuleInitializationLevel p_level) {
  347. %s
  348. }
  349. """ % (
  350. includes_cpp,
  351. initialize_cpp,
  352. uninitialize_cpp,
  353. )
  354. # NOTE: It is safe to generate this file here, since this is still executed serially
  355. with open("modules/register_module_types.gen.cpp", "w") as f:
  356. f.write(modules_cpp)
  357. def convert_custom_modules_path(path):
  358. if not path:
  359. return path
  360. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  361. err_msg = "Build option 'custom_modules' must %s"
  362. if not os.path.isdir(path):
  363. raise ValueError(err_msg % "point to an existing directory.")
  364. if path == os.path.realpath("modules"):
  365. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  366. return path
  367. def disable_module(self):
  368. self.disabled_modules.append(self.current_module)
  369. def module_add_dependencies(self, module, dependencies, optional=False):
  370. """
  371. Adds dependencies for a given module.
  372. Meant to be used in module `can_build` methods.
  373. """
  374. if module not in self.module_dependencies:
  375. self.module_dependencies[module] = [[], []]
  376. if optional:
  377. self.module_dependencies[module][1].extend(dependencies)
  378. else:
  379. self.module_dependencies[module][0].extend(dependencies)
  380. def module_check_dependencies(self, module):
  381. """
  382. Checks if module dependencies are enabled for a given module,
  383. and prints a warning if they aren't.
  384. Meant to be used in module `can_build` methods.
  385. Returns a boolean (True if dependencies are satisfied).
  386. """
  387. missing_deps = []
  388. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  389. for dep in required_deps:
  390. opt = "module_{}_enabled".format(dep)
  391. if not opt in self or not self[opt]:
  392. missing_deps.append(dep)
  393. if missing_deps != []:
  394. print(
  395. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  396. module, ", ".join(missing_deps)
  397. )
  398. )
  399. return False
  400. else:
  401. return True
  402. def sort_module_list(env):
  403. out = OrderedDict()
  404. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  405. frontier = list(env.module_list.keys())
  406. explored = []
  407. while len(frontier):
  408. cur = frontier.pop()
  409. deps_list = deps[cur] if cur in deps else []
  410. if len(deps_list) and any([d not in explored for d in deps_list]):
  411. # Will explore later, after its dependencies
  412. frontier.insert(0, cur)
  413. continue
  414. explored.append(cur)
  415. for k in explored:
  416. env.module_list.move_to_end(k)
  417. def use_windows_spawn_fix(self, platform=None):
  418. if os.name != "nt":
  419. return # not needed, only for windows
  420. # On Windows, due to the limited command line length, when creating a static library
  421. # from a very high number of objects SCons will invoke "ar" once per object file;
  422. # that makes object files with same names to be overwritten so the last wins and
  423. # the library loses symbols defined by overwritten objects.
  424. # By enabling quick append instead of the default mode (replacing), libraries will
  425. # got built correctly regardless the invocation strategy.
  426. # Furthermore, since SCons will rebuild the library from scratch when an object file
  427. # changes, no multiple versions of the same object file will be present.
  428. self.Replace(ARFLAGS="q")
  429. def mySubProcess(cmdline, env):
  430. startupinfo = subprocess.STARTUPINFO()
  431. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  432. popen_args = {
  433. "stdin": subprocess.PIPE,
  434. "stdout": subprocess.PIPE,
  435. "stderr": subprocess.PIPE,
  436. "startupinfo": startupinfo,
  437. "shell": False,
  438. "env": env,
  439. }
  440. if sys.version_info >= (3, 7, 0):
  441. popen_args["text"] = True
  442. proc = subprocess.Popen(cmdline, **popen_args)
  443. _, err = proc.communicate()
  444. rv = proc.wait()
  445. if rv:
  446. print("=====")
  447. print(err)
  448. print("=====")
  449. return rv
  450. def mySpawn(sh, escape, cmd, args, env):
  451. newargs = " ".join(args[1:])
  452. cmdline = cmd + " " + newargs
  453. rv = 0
  454. env = {str(key): str(value) for key, value in iter(env.items())}
  455. if len(cmdline) > 32000 and cmd.endswith("ar"):
  456. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  457. for i in range(3, len(args)):
  458. rv = mySubProcess(cmdline + args[i], env)
  459. if rv:
  460. break
  461. else:
  462. rv = mySubProcess(cmdline, env)
  463. return rv
  464. self["SPAWN"] = mySpawn
  465. def no_verbose(sys, env):
  466. colors = {}
  467. # Colors are disabled in non-TTY environments such as pipes. This means
  468. # that if output is redirected to a file, it will not contain color codes
  469. if sys.stdout.isatty():
  470. colors["blue"] = "\033[0;94m"
  471. colors["bold_blue"] = "\033[1;94m"
  472. colors["reset"] = "\033[0m"
  473. else:
  474. colors["blue"] = ""
  475. colors["bold_blue"] = ""
  476. colors["reset"] = ""
  477. # There is a space before "..." to ensure that source file names can be
  478. # Ctrl + clicked in the VS Code terminal.
  479. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  480. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  481. )
  482. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  483. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  484. )
  485. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(
  486. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  487. )
  488. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(
  489. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  490. )
  491. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(
  492. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  493. )
  494. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(
  495. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  496. )
  497. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(
  498. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  499. )
  500. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(
  501. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  502. )
  503. env.Append(CXXCOMSTR=[compile_source_message])
  504. env.Append(CCCOMSTR=[compile_source_message])
  505. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  506. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  507. env.Append(ARCOMSTR=[link_library_message])
  508. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  509. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  510. env.Append(LINKCOMSTR=[link_program_message])
  511. env.Append(JARCOMSTR=[java_library_message])
  512. env.Append(JAVACCOMSTR=[java_compile_source_message])
  513. def detect_visual_c_compiler_version(tools_env):
  514. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  515. # (see the SCons documentation for more information on what it does)...
  516. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  517. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  518. # the proper vc version that will be called
  519. # 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.).
  520. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  521. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  522. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  523. # the following string values:
  524. # "" Compiler not detected
  525. # "amd64" Native 64 bit compiler
  526. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  527. # "x86" Native 32 bit compiler
  528. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  529. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  530. # and similar architectures/compilers
  531. # Set chosen compiler to "not detected"
  532. vc_chosen_compiler_index = -1
  533. vc_chosen_compiler_str = ""
  534. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  535. if "VCINSTALLDIR" in tools_env:
  536. # print("Checking VCINSTALLDIR")
  537. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  538. # First test if amd64 and amd64_x86 compilers are present in the path
  539. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  540. if vc_amd64_compiler_detection_index > -1:
  541. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  542. vc_chosen_compiler_str = "amd64"
  543. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  544. if vc_amd64_x86_compiler_detection_index > -1 and (
  545. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  546. ):
  547. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  548. vc_chosen_compiler_str = "amd64_x86"
  549. # Now check the 32 bit compilers
  550. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  551. if vc_x86_compiler_detection_index > -1 and (
  552. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  553. ):
  554. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  555. vc_chosen_compiler_str = "x86"
  556. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  557. if vc_x86_amd64_compiler_detection_index > -1 and (
  558. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  559. ):
  560. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  561. vc_chosen_compiler_str = "x86_amd64"
  562. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  563. if "VCTOOLSINSTALLDIR" in tools_env:
  564. # Newer versions have a different path available
  565. vc_amd64_compiler_detection_index = (
  566. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  567. )
  568. if vc_amd64_compiler_detection_index > -1:
  569. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  570. vc_chosen_compiler_str = "amd64"
  571. vc_amd64_x86_compiler_detection_index = (
  572. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  573. )
  574. if vc_amd64_x86_compiler_detection_index > -1 and (
  575. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  576. ):
  577. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  578. vc_chosen_compiler_str = "amd64_x86"
  579. vc_x86_compiler_detection_index = (
  580. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  581. )
  582. if vc_x86_compiler_detection_index > -1 and (
  583. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  584. ):
  585. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  586. vc_chosen_compiler_str = "x86"
  587. vc_x86_amd64_compiler_detection_index = (
  588. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  589. )
  590. if vc_x86_amd64_compiler_detection_index > -1 and (
  591. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  592. ):
  593. vc_chosen_compiler_str = "x86_amd64"
  594. return vc_chosen_compiler_str
  595. def find_visual_c_batch_file(env):
  596. from SCons.Tool.MSCommon.vc import (
  597. get_default_version,
  598. get_host_target,
  599. find_batch_file,
  600. )
  601. # Syntax changed in SCons 4.4.0.
  602. from SCons import __version__ as scons_raw_version
  603. scons_ver = env._get_major_minor_revision(scons_raw_version)
  604. version = get_default_version(env)
  605. if scons_ver >= (4, 4, 0):
  606. (host_platform, target_platform, _) = get_host_target(env, version)
  607. else:
  608. (host_platform, target_platform, _) = get_host_target(env)
  609. return find_batch_file(env, version, host_platform, target_platform)[0]
  610. def generate_cpp_hint_file(filename):
  611. if os.path.isfile(filename):
  612. # Don't overwrite an existing hint file since the user may have customized it.
  613. pass
  614. else:
  615. try:
  616. with open(filename, "w") as fd:
  617. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  618. except OSError:
  619. print("Could not write cpp.hint file.")
  620. def glob_recursive(pattern, node="."):
  621. from SCons import Node
  622. from SCons.Script import Glob
  623. results = []
  624. for f in Glob(str(node) + "/*", source=True):
  625. if type(f) is Node.FS.Dir:
  626. results += glob_recursive(pattern, f)
  627. results += Glob(str(node) + "/" + pattern, source=True)
  628. return results
  629. def add_to_vs_project(env, sources):
  630. for x in sources:
  631. if type(x) == type(""):
  632. fname = env.File(x).path
  633. else:
  634. fname = env.File(x)[0].path
  635. pieces = fname.split(".")
  636. if len(pieces) > 0:
  637. basename = pieces[0]
  638. basename = basename.replace("\\\\", "/")
  639. if os.path.isfile(basename + ".h"):
  640. env.vs_incs += [basename + ".h"]
  641. elif os.path.isfile(basename + ".hpp"):
  642. env.vs_incs += [basename + ".hpp"]
  643. if os.path.isfile(basename + ".c"):
  644. env.vs_srcs += [basename + ".c"]
  645. elif os.path.isfile(basename + ".cpp"):
  646. env.vs_srcs += [basename + ".cpp"]
  647. def generate_vs_project(env, original_args, project_name="godot"):
  648. batch_file = find_visual_c_batch_file(env)
  649. filtered_args = original_args.copy()
  650. # Ignore the "vsproj" option to not regenerate the VS project on every build
  651. filtered_args.pop("vsproj", None)
  652. # The "platform" option is ignored because only the Windows platform is currently supported for VS projects
  653. filtered_args.pop("platform", None)
  654. # The "target" option is ignored due to the way how targets configuration is performed for VS projects (there is a separate project configuration for each target)
  655. filtered_args.pop("target", None)
  656. # The "progress" option is ignored as the current compilation progress indication doesn't work in VS
  657. filtered_args.pop("progress", None)
  658. if batch_file:
  659. class ModuleConfigs(Mapping):
  660. # This version information (Win32, x64, Debug, Release) seems to be
  661. # required for Visual Studio to understand that it needs to generate an NMAKE
  662. # project. Do not modify without knowing what you are doing.
  663. PLATFORMS = ["Win32", "x64"]
  664. PLATFORM_IDS = ["x86_32", "x86_64"]
  665. CONFIGURATIONS = ["editor", "template_release", "template_debug"]
  666. DEV_SUFFIX = ".dev" if env["dev_build"] else ""
  667. @staticmethod
  668. def for_every_variant(value):
  669. return [value for _ in range(len(ModuleConfigs.CONFIGURATIONS) * len(ModuleConfigs.PLATFORMS))]
  670. def __init__(self):
  671. shared_targets_array = []
  672. self.names = []
  673. self.arg_dict = {
  674. "variant": [],
  675. "runfile": shared_targets_array,
  676. "buildtarget": shared_targets_array,
  677. "cpppaths": [],
  678. "cppdefines": [],
  679. "cmdargs": [],
  680. }
  681. self.add_mode() # default
  682. def add_mode(
  683. self,
  684. name: str = "",
  685. includes: str = "",
  686. cli_args: str = "",
  687. defines=None,
  688. ):
  689. if defines is None:
  690. defines = []
  691. self.names.append(name)
  692. self.arg_dict["variant"] += [
  693. f'{config}{f"_[{name}]" if name else ""}|{platform}'
  694. for config in ModuleConfigs.CONFIGURATIONS
  695. for platform in ModuleConfigs.PLATFORMS
  696. ]
  697. self.arg_dict["runfile"] += [
  698. f'bin\\godot.windows.{config}{ModuleConfigs.DEV_SUFFIX}{".double" if env["precision"] == "double" else ""}.{plat_id}{f".{name}" if name else ""}.exe'
  699. for config in ModuleConfigs.CONFIGURATIONS
  700. for plat_id in ModuleConfigs.PLATFORM_IDS
  701. ]
  702. self.arg_dict["cpppaths"] += ModuleConfigs.for_every_variant(env["CPPPATH"] + [includes])
  703. self.arg_dict["cppdefines"] += ModuleConfigs.for_every_variant(list(env["CPPDEFINES"]) + defines)
  704. self.arg_dict["cmdargs"] += ModuleConfigs.for_every_variant(cli_args)
  705. def build_commandline(self, commands):
  706. configuration_getter = (
  707. "$(Configuration"
  708. + "".join([f'.Replace("{name}", "")' for name in self.names[1:]])
  709. + '.Replace("_[]", "")'
  710. + ")"
  711. )
  712. common_build_prefix = [
  713. 'cmd /V /C set "plat=$(PlatformTarget)"',
  714. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  715. 'call "' + batch_file + '" !plat!',
  716. ]
  717. # Windows allows us to have spaces in paths, so we need
  718. # to double quote off the directory. However, the path ends
  719. # in a backslash, so we need to remove this, lest it escape the
  720. # last double quote off, confusing MSBuild
  721. common_build_postfix = [
  722. "--directory=\"$(ProjectDir.TrimEnd('\\'))\"",
  723. "platform=windows",
  724. f"target={configuration_getter}",
  725. "progress=no",
  726. ]
  727. for arg, value in filtered_args.items():
  728. common_build_postfix.append(f"{arg}={value}")
  729. result = " ^& ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)])
  730. return result
  731. # Mappings interface definitions
  732. def __iter__(self) -> Iterator[str]:
  733. for x in self.arg_dict:
  734. yield x
  735. def __len__(self) -> int:
  736. return len(self.names)
  737. def __getitem__(self, k: str):
  738. return self.arg_dict[k]
  739. add_to_vs_project(env, env.core_sources)
  740. add_to_vs_project(env, env.drivers_sources)
  741. add_to_vs_project(env, env.main_sources)
  742. add_to_vs_project(env, env.modules_sources)
  743. add_to_vs_project(env, env.scene_sources)
  744. add_to_vs_project(env, env.servers_sources)
  745. if env["tests"]:
  746. add_to_vs_project(env, env.tests_sources)
  747. if env.editor_build:
  748. add_to_vs_project(env, env.editor_sources)
  749. for header in glob_recursive("**/*.h"):
  750. env.vs_incs.append(str(header))
  751. module_configs = ModuleConfigs()
  752. if env.get("module_mono_enabled"):
  753. mono_defines = [("GD_MONO_HOT_RELOAD",)] if env.editor_build else []
  754. module_configs.add_mode(
  755. "mono",
  756. cli_args="module_mono_enabled=yes",
  757. defines=mono_defines,
  758. )
  759. scons_cmd = "scons"
  760. path_to_venv = os.getenv("VIRTUAL_ENV")
  761. path_to_scons_exe = Path(str(path_to_venv)) / "Scripts" / "scons.exe"
  762. if path_to_venv and path_to_scons_exe.exists():
  763. scons_cmd = str(path_to_scons_exe)
  764. env["MSVSBUILDCOM"] = module_configs.build_commandline(scons_cmd)
  765. env["MSVSREBUILDCOM"] = module_configs.build_commandline(f"{scons_cmd} vsproj=yes")
  766. env["MSVSCLEANCOM"] = module_configs.build_commandline(f"{scons_cmd} --clean")
  767. if not env.get("MSVS"):
  768. env["MSVS"]["PROJECTSUFFIX"] = ".vcxproj"
  769. env["MSVS"]["SOLUTIONSUFFIX"] = ".sln"
  770. env.MSVSProject(
  771. target=["#" + project_name + env["MSVSPROJECTSUFFIX"]],
  772. incs=env.vs_incs,
  773. srcs=env.vs_srcs,
  774. auto_build_solution=1,
  775. **module_configs,
  776. )
  777. else:
  778. print("Could not locate Visual Studio batch file to set up the build environment. Not generating VS project.")
  779. def precious_program(env, program, sources, **args):
  780. program = env.ProgramOriginal(program, sources, **args)
  781. env.Precious(program)
  782. return program
  783. def add_shared_library(env, name, sources, **args):
  784. library = env.SharedLibrary(name, sources, **args)
  785. env.NoCache(library)
  786. return library
  787. def add_library(env, name, sources, **args):
  788. library = env.Library(name, sources, **args)
  789. env.NoCache(library)
  790. return library
  791. def add_program(env, name, sources, **args):
  792. program = env.Program(name, sources, **args)
  793. env.NoCache(program)
  794. return program
  795. def CommandNoCache(env, target, sources, command, **args):
  796. result = env.Command(target, sources, command, **args)
  797. env.NoCache(result)
  798. return result
  799. def Run(env, function, short_message, subprocess=True):
  800. from SCons.Script import Action
  801. from platform_methods import run_in_subprocess
  802. output_print = short_message if not env["verbose"] else ""
  803. if not subprocess:
  804. return Action(function, output_print)
  805. else:
  806. return Action(run_in_subprocess(function), output_print)
  807. def detect_darwin_sdk_path(platform, env):
  808. sdk_name = ""
  809. if platform == "macos":
  810. sdk_name = "macosx"
  811. var_name = "MACOS_SDK_PATH"
  812. elif platform == "ios":
  813. sdk_name = "iphoneos"
  814. var_name = "IOS_SDK_PATH"
  815. elif platform == "iossimulator":
  816. sdk_name = "iphonesimulator"
  817. var_name = "IOS_SDK_PATH"
  818. else:
  819. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  820. if not env[var_name]:
  821. try:
  822. sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8")
  823. if sdk_path:
  824. env[var_name] = sdk_path
  825. except (subprocess.CalledProcessError, OSError):
  826. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  827. raise
  828. def is_vanilla_clang(env):
  829. if not using_clang(env):
  830. return False
  831. try:
  832. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  833. except (subprocess.CalledProcessError, OSError):
  834. print("Couldn't parse CXX environment variable to infer compiler version.")
  835. return False
  836. return not version.startswith("Apple")
  837. def get_compiler_version(env):
  838. """
  839. Returns a dictionary with various version information:
  840. - major, minor, patch: Version following semantic versioning system
  841. - metadata1, metadata2: Extra information
  842. - date: Date of the build
  843. """
  844. ret = {
  845. "major": -1,
  846. "minor": -1,
  847. "patch": -1,
  848. "metadata1": None,
  849. "metadata2": None,
  850. "date": None,
  851. }
  852. if not env.msvc:
  853. # Not using -dumpversion as some GCC distros only return major, and
  854. # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803
  855. try:
  856. version = subprocess.check_output([env.subst(env["CXX"]), "--version"]).strip().decode("utf-8")
  857. except (subprocess.CalledProcessError, OSError):
  858. print("Couldn't parse CXX environment variable to infer compiler version.")
  859. return ret
  860. else:
  861. # TODO: Implement for MSVC
  862. return ret
  863. match = re.search(
  864. r"(?:(?<=version )|(?<=\) )|(?<=^))"
  865. r"(?P<major>\d+)"
  866. r"(?:\.(?P<minor>\d*))?"
  867. r"(?:\.(?P<patch>\d*))?"
  868. r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?"
  869. r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?"
  870. r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?",
  871. version,
  872. )
  873. if match is not None:
  874. for key, value in match.groupdict().items():
  875. if value is not None:
  876. ret[key] = value
  877. # Transform semantic versioning to integers
  878. for key in ["major", "minor", "patch"]:
  879. ret[key] = int(ret[key] or -1)
  880. return ret
  881. def using_gcc(env):
  882. return "gcc" in os.path.basename(env["CC"])
  883. def using_clang(env):
  884. return "clang" in os.path.basename(env["CC"])
  885. def using_emcc(env):
  886. return "emcc" in os.path.basename(env["CC"])
  887. def show_progress(env):
  888. import sys
  889. from SCons.Script import Progress, Command, AlwaysBuild
  890. screen = sys.stdout
  891. # Progress reporting is not available in non-TTY environments since it
  892. # messes with the output (for example, when writing to a file)
  893. show_progress = env["progress"] and sys.stdout.isatty()
  894. node_count = 0
  895. node_count_max = 0
  896. node_count_interval = 1
  897. node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
  898. import time, math
  899. class cache_progress:
  900. # The default is 1 GB cache and 12 hours half life
  901. def __init__(self, path=None, limit=1073741824, half_life=43200):
  902. self.path = path
  903. self.limit = limit
  904. self.exponent_scale = math.log(2) / half_life
  905. if env["verbose"] and path != None:
  906. screen.write(
  907. "Current cache limit is {} (used: {})\n".format(
  908. self.convert_size(limit), self.convert_size(self.get_size(path))
  909. )
  910. )
  911. self.delete(self.file_list())
  912. def __call__(self, node, *args, **kw):
  913. nonlocal node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  914. if show_progress:
  915. # Print the progress percentage
  916. node_count += node_count_interval
  917. if node_count_max > 0 and node_count <= node_count_max:
  918. screen.write("\r[%3d%%] " % (node_count * 100 / node_count_max))
  919. screen.flush()
  920. elif node_count_max > 0 and node_count > node_count_max:
  921. screen.write("\r[100%] ")
  922. screen.flush()
  923. else:
  924. screen.write("\r[Initial build] ")
  925. screen.flush()
  926. def delete(self, files):
  927. if len(files) == 0:
  928. return
  929. if env["verbose"]:
  930. # Utter something
  931. screen.write("\rPurging %d %s from cache...\n" % (len(files), len(files) > 1 and "files" or "file"))
  932. [os.remove(f) for f in files]
  933. def file_list(self):
  934. if self.path is None:
  935. # Nothing to do
  936. return []
  937. # Gather a list of (filename, (size, atime)) within the
  938. # cache directory
  939. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, "*", "*"))]
  940. if file_stat == []:
  941. # Nothing to do
  942. return []
  943. # Weight the cache files by size (assumed to be roughly
  944. # proportional to the recompilation time) times an exponential
  945. # decay since the ctime, and return a list with the entries
  946. # (filename, size, weight).
  947. current_time = time.time()
  948. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  949. # Sort by the most recently accessed files (most sensible to keep) first
  950. file_stat.sort(key=lambda x: x[2])
  951. # Search for the first entry where the storage limit is
  952. # reached
  953. sum, mark = 0, None
  954. for i, x in enumerate(file_stat):
  955. sum += x[1]
  956. if sum > self.limit:
  957. mark = i
  958. break
  959. if mark is None:
  960. return []
  961. else:
  962. return [x[0] for x in file_stat[mark:]]
  963. def convert_size(self, size_bytes):
  964. if size_bytes == 0:
  965. return "0 bytes"
  966. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  967. i = int(math.floor(math.log(size_bytes, 1024)))
  968. p = math.pow(1024, i)
  969. s = round(size_bytes / p, 2)
  970. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  971. def get_size(self, start_path="."):
  972. total_size = 0
  973. for dirpath, dirnames, filenames in os.walk(start_path):
  974. for f in filenames:
  975. fp = os.path.join(dirpath, f)
  976. total_size += os.path.getsize(fp)
  977. return total_size
  978. def progress_finish(target, source, env):
  979. nonlocal node_count, progressor
  980. try:
  981. with open(node_count_fname, "w") as f:
  982. f.write("%d\n" % node_count)
  983. progressor.delete(progressor.file_list())
  984. except Exception:
  985. pass
  986. try:
  987. with open(node_count_fname) as f:
  988. node_count_max = int(f.readline())
  989. except Exception:
  990. pass
  991. cache_directory = os.environ.get("SCONS_CACHE")
  992. # Simple cache pruning, attached to SCons' progress callback. Trim the
  993. # cache directory to a size not larger than cache_limit.
  994. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  995. progressor = cache_progress(cache_directory, cache_limit)
  996. Progress(progressor, interval=node_count_interval)
  997. progress_finish_command = Command("progress_finish", [], progress_finish)
  998. AlwaysBuild(progress_finish_command)
  999. def dump(env):
  1000. # Dumps latest build information for debugging purposes and external tools.
  1001. from json import dump
  1002. def non_serializable(obj):
  1003. return "<<non-serializable: %s>>" % (type(obj).__qualname__)
  1004. with open(".scons_env.json", "w") as f:
  1005. dump(env.Dictionary(), f, indent=4, default=non_serializable)