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. # Add all the gen.cpp files in the SCU directory
  83. add_source_files_orig(self, sources, subdir + "scu/scu_*.gen.cpp", True)
  84. return True
  85. return False
  86. # Either builds the folder using the SCU system,
  87. # or reverts to regular build.
  88. def add_source_files(self, sources, files, allow_gen=False):
  89. if not add_source_files_scu(self, sources, files, allow_gen):
  90. # Wraps the original function when scu build is not active.
  91. add_source_files_orig(self, sources, files, allow_gen)
  92. return False
  93. return True
  94. def disable_warnings(self):
  95. # 'self' is the environment
  96. if self.msvc:
  97. # We have to remove existing warning level defines before appending /w,
  98. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  99. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  100. self["CFLAGS"] = [x for x in self["CFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  101. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not (x.startswith("/W") or x.startswith("/w"))]
  102. self.AppendUnique(CCFLAGS=["/w"])
  103. else:
  104. self.AppendUnique(CCFLAGS=["-w"])
  105. def force_optimization_on_debug(self):
  106. # 'self' is the environment
  107. if self["target"] == "template_release":
  108. return
  109. if self.msvc:
  110. # We have to remove existing optimization level defines before appending /O2,
  111. # otherwise we get: "warning D9025 : overriding '/0d' with '/02'"
  112. self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x.startswith("/O")]
  113. self["CFLAGS"] = [x for x in self["CFLAGS"] if not x.startswith("/O")]
  114. self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x.startswith("/O")]
  115. self.AppendUnique(CCFLAGS=["/O2"])
  116. else:
  117. self.AppendUnique(CCFLAGS=["-O3"])
  118. def add_module_version_string(self, s):
  119. self.module_version_string += "." + s
  120. def get_version_info(module_version_string="", silent=False):
  121. build_name = "custom_build"
  122. if os.getenv("BUILD_NAME") != None:
  123. build_name = str(os.getenv("BUILD_NAME"))
  124. if not silent:
  125. print(f"Using custom build name: '{build_name}'.")
  126. import version
  127. version_info = {
  128. "short_name": str(version.short_name),
  129. "name": str(version.name),
  130. "major": int(version.major),
  131. "minor": int(version.minor),
  132. "patch": int(version.patch),
  133. "status": str(version.status),
  134. "build": str(build_name),
  135. "module_config": str(version.module_config) + module_version_string,
  136. "year": int(version.year),
  137. "website": str(version.website),
  138. "docs_branch": str(version.docs),
  139. }
  140. # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
  141. # so this define provides a way to override it without having to modify the source.
  142. if os.getenv("GODOT_VERSION_STATUS") != None:
  143. version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
  144. if not silent:
  145. print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
  146. # Parse Git hash if we're in a Git repo.
  147. githash = ""
  148. gitfolder = ".git"
  149. if os.path.isfile(".git"):
  150. module_folder = open(".git", "r").readline().strip()
  151. if module_folder.startswith("gitdir: "):
  152. gitfolder = module_folder[8:]
  153. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  154. head = open(os.path.join(gitfolder, "HEAD"), "r", encoding="utf8").readline().strip()
  155. if head.startswith("ref: "):
  156. ref = head[5:]
  157. # If this directory is a Git worktree instead of a root clone.
  158. parts = gitfolder.split("/")
  159. if len(parts) > 2 and parts[-2] == "worktrees":
  160. gitfolder = "/".join(parts[0:-2])
  161. head = os.path.join(gitfolder, ref)
  162. packedrefs = os.path.join(gitfolder, "packed-refs")
  163. if os.path.isfile(head):
  164. githash = open(head, "r").readline().strip()
  165. elif os.path.isfile(packedrefs):
  166. # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash.
  167. # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html
  168. for line in open(packedrefs, "r").read().splitlines():
  169. if line.startswith("#"):
  170. continue
  171. (line_hash, line_ref) = line.split(" ")
  172. if ref == line_ref:
  173. githash = line_hash
  174. break
  175. else:
  176. githash = head
  177. version_info["git_hash"] = githash
  178. return version_info
  179. def generate_version_header(module_version_string=""):
  180. version_info = get_version_info(module_version_string)
  181. # NOTE: It is safe to generate these files here, since this is still executed serially.
  182. f = open("core/version_generated.gen.h", "w")
  183. f.write(
  184. """/* THIS FILE IS GENERATED DO NOT EDIT */
  185. #ifndef VERSION_GENERATED_GEN_H
  186. #define VERSION_GENERATED_GEN_H
  187. #define VERSION_SHORT_NAME "{short_name}"
  188. #define VERSION_NAME "{name}"
  189. #define VERSION_MAJOR {major}
  190. #define VERSION_MINOR {minor}
  191. #define VERSION_PATCH {patch}
  192. #define VERSION_STATUS "{status}"
  193. #define VERSION_BUILD "{build}"
  194. #define VERSION_MODULE_CONFIG "{module_config}"
  195. #define VERSION_YEAR {year}
  196. #define VERSION_WEBSITE "{website}"
  197. #define VERSION_DOCS_BRANCH "{docs_branch}"
  198. #define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH
  199. #endif // VERSION_GENERATED_GEN_H
  200. """.format(
  201. **version_info
  202. )
  203. )
  204. f.close()
  205. fhash = open("core/version_hash.gen.cpp", "w")
  206. fhash.write(
  207. """/* THIS FILE IS GENERATED DO NOT EDIT */
  208. #include "core/version.h"
  209. const char *const VERSION_HASH = "{git_hash}";
  210. """.format(
  211. **version_info
  212. )
  213. )
  214. fhash.close()
  215. def parse_cg_file(fname, uniforms, sizes, conditionals):
  216. fs = open(fname, "r")
  217. line = fs.readline()
  218. while line:
  219. if re.match(r"^\s*uniform", line):
  220. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  221. type = res.groups(1)
  222. name = res.groups(2)
  223. uniforms.append(name)
  224. if type.find("texobj") != -1:
  225. sizes.append(1)
  226. else:
  227. t = re.match(r"float(\d)x(\d)", type)
  228. if t:
  229. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  230. else:
  231. t = re.match(r"float(\d)", type)
  232. sizes.append(int(t.groups(1)))
  233. if line.find("[branch]") != -1:
  234. conditionals.append(name)
  235. line = fs.readline()
  236. fs.close()
  237. def get_cmdline_bool(option, default):
  238. """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line,
  239. and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings.
  240. """
  241. from SCons.Script import ARGUMENTS
  242. from SCons.Variables.BoolVariable import _text2bool
  243. cmdline_val = ARGUMENTS.get(option)
  244. if cmdline_val is not None:
  245. return _text2bool(cmdline_val)
  246. else:
  247. return default
  248. def detect_modules(search_path, recursive=False):
  249. """Detects and collects a list of C++ modules at specified path
  250. `search_path` - a directory path containing modules. The path may point to
  251. a single module, which may have other nested modules. A module must have
  252. "register_types.h", "SCsub", "config.py" files created to be detected.
  253. `recursive` - if `True`, then all subdirectories are searched for modules as
  254. specified by the `search_path`, otherwise collects all modules under the
  255. `search_path` directory. If the `search_path` is a module, it is collected
  256. in all cases.
  257. Returns an `OrderedDict` with module names as keys, and directory paths as
  258. values. If a path is relative, then it is a built-in module. If a path is
  259. absolute, then it is a custom module collected outside of the engine source.
  260. """
  261. modules = OrderedDict()
  262. def add_module(path):
  263. module_name = os.path.basename(path)
  264. module_path = path.replace("\\", "/") # win32
  265. modules[module_name] = module_path
  266. def is_engine(path):
  267. # Prevent recursively detecting modules in self and other
  268. # Godot sources when using `custom_modules` build option.
  269. version_path = os.path.join(path, "version.py")
  270. if os.path.exists(version_path):
  271. with open(version_path) as f:
  272. if 'short_name = "godot"' in f.read():
  273. return True
  274. return False
  275. def get_files(path):
  276. files = glob.glob(os.path.join(path, "*"))
  277. # Sort so that `register_module_types` does not change that often,
  278. # and plugins are registered in alphabetic order as well.
  279. files.sort()
  280. return files
  281. if not recursive:
  282. if is_module(search_path):
  283. add_module(search_path)
  284. for path in get_files(search_path):
  285. if is_engine(path):
  286. continue
  287. if is_module(path):
  288. add_module(path)
  289. else:
  290. to_search = [search_path]
  291. while to_search:
  292. path = to_search.pop()
  293. if is_module(path):
  294. add_module(path)
  295. for child in get_files(path):
  296. if not os.path.isdir(child):
  297. continue
  298. if is_engine(child):
  299. continue
  300. to_search.insert(0, child)
  301. return modules
  302. def is_module(path):
  303. if not os.path.isdir(path):
  304. return False
  305. must_exist = ["register_types.h", "SCsub", "config.py"]
  306. for f in must_exist:
  307. if not os.path.exists(os.path.join(path, f)):
  308. return False
  309. return True
  310. def write_disabled_classes(class_list):
  311. f = open("core/disabled_classes.gen.h", "w")
  312. f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  313. f.write("#ifndef DISABLED_CLASSES_GEN_H\n")
  314. f.write("#define DISABLED_CLASSES_GEN_H\n\n")
  315. for c in class_list:
  316. cs = c.strip()
  317. if cs != "":
  318. f.write("#define ClassDB_Disable_" + cs + " 1\n")
  319. f.write("\n#endif\n")
  320. def write_modules(modules):
  321. includes_cpp = ""
  322. initialize_cpp = ""
  323. uninitialize_cpp = ""
  324. for name, path in modules.items():
  325. try:
  326. with open(os.path.join(path, "register_types.h")):
  327. includes_cpp += '#include "' + path + '/register_types.h"\n'
  328. initialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  329. initialize_cpp += "\tinitialize_" + name + "_module(p_level);\n"
  330. initialize_cpp += "#endif\n"
  331. uninitialize_cpp += "#ifdef MODULE_" + name.upper() + "_ENABLED\n"
  332. uninitialize_cpp += "\tuninitialize_" + name + "_module(p_level);\n"
  333. uninitialize_cpp += "#endif\n"
  334. except OSError:
  335. pass
  336. modules_cpp = """// register_module_types.gen.cpp
  337. /* THIS FILE IS GENERATED DO NOT EDIT */
  338. #include "register_module_types.h"
  339. #include "modules/modules_enabled.gen.h"
  340. %s
  341. void initialize_modules(ModuleInitializationLevel p_level) {
  342. %s
  343. }
  344. void uninitialize_modules(ModuleInitializationLevel p_level) {
  345. %s
  346. }
  347. """ % (
  348. includes_cpp,
  349. initialize_cpp,
  350. uninitialize_cpp,
  351. )
  352. # NOTE: It is safe to generate this file here, since this is still executed serially
  353. with open("modules/register_module_types.gen.cpp", "w") as f:
  354. f.write(modules_cpp)
  355. def convert_custom_modules_path(path):
  356. if not path:
  357. return path
  358. path = os.path.realpath(os.path.expanduser(os.path.expandvars(path)))
  359. err_msg = "Build option 'custom_modules' must %s"
  360. if not os.path.isdir(path):
  361. raise ValueError(err_msg % "point to an existing directory.")
  362. if path == os.path.realpath("modules"):
  363. raise ValueError(err_msg % "be a directory other than built-in `modules` directory.")
  364. return path
  365. def disable_module(self):
  366. self.disabled_modules.append(self.current_module)
  367. def module_add_dependencies(self, module, dependencies, optional=False):
  368. """
  369. Adds dependencies for a given module.
  370. Meant to be used in module `can_build` methods.
  371. """
  372. if module not in self.module_dependencies:
  373. self.module_dependencies[module] = [[], []]
  374. if optional:
  375. self.module_dependencies[module][1].extend(dependencies)
  376. else:
  377. self.module_dependencies[module][0].extend(dependencies)
  378. def module_check_dependencies(self, module):
  379. """
  380. Checks if module dependencies are enabled for a given module,
  381. and prints a warning if they aren't.
  382. Meant to be used in module `can_build` methods.
  383. Returns a boolean (True if dependencies are satisfied).
  384. """
  385. missing_deps = []
  386. required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
  387. for dep in required_deps:
  388. opt = "module_{}_enabled".format(dep)
  389. if not opt in self or not self[opt]:
  390. missing_deps.append(dep)
  391. if missing_deps != []:
  392. print(
  393. "Disabling '{}' module as the following dependencies are not satisfied: {}".format(
  394. module, ", ".join(missing_deps)
  395. )
  396. )
  397. return False
  398. else:
  399. return True
  400. def sort_module_list(env):
  401. out = OrderedDict()
  402. deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
  403. frontier = list(env.module_list.keys())
  404. explored = []
  405. while len(frontier):
  406. cur = frontier.pop()
  407. deps_list = deps[cur] if cur in deps else []
  408. if len(deps_list) and any([d not in explored for d in deps_list]):
  409. # Will explore later, after its dependencies
  410. frontier.insert(0, cur)
  411. continue
  412. explored.append(cur)
  413. for k in explored:
  414. env.module_list.move_to_end(k)
  415. def use_windows_spawn_fix(self, platform=None):
  416. if os.name != "nt":
  417. return # not needed, only for windows
  418. # On Windows, due to the limited command line length, when creating a static library
  419. # from a very high number of objects SCons will invoke "ar" once per object file;
  420. # that makes object files with same names to be overwritten so the last wins and
  421. # the library loses symbols defined by overwritten objects.
  422. # By enabling quick append instead of the default mode (replacing), libraries will
  423. # got built correctly regardless the invocation strategy.
  424. # Furthermore, since SCons will rebuild the library from scratch when an object file
  425. # changes, no multiple versions of the same object file will be present.
  426. self.Replace(ARFLAGS="q")
  427. def mySubProcess(cmdline, env):
  428. startupinfo = subprocess.STARTUPINFO()
  429. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  430. popen_args = {
  431. "stdin": subprocess.PIPE,
  432. "stdout": subprocess.PIPE,
  433. "stderr": subprocess.PIPE,
  434. "startupinfo": startupinfo,
  435. "shell": False,
  436. "env": env,
  437. }
  438. if sys.version_info >= (3, 7, 0):
  439. popen_args["text"] = True
  440. proc = subprocess.Popen(cmdline, **popen_args)
  441. _, err = proc.communicate()
  442. rv = proc.wait()
  443. if rv:
  444. print("=====")
  445. print(err)
  446. print("=====")
  447. return rv
  448. def mySpawn(sh, escape, cmd, args, env):
  449. newargs = " ".join(args[1:])
  450. cmdline = cmd + " " + newargs
  451. rv = 0
  452. env = {str(key): str(value) for key, value in iter(env.items())}
  453. if len(cmdline) > 32000 and cmd.endswith("ar"):
  454. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  455. for i in range(3, len(args)):
  456. rv = mySubProcess(cmdline + args[i], env)
  457. if rv:
  458. break
  459. else:
  460. rv = mySubProcess(cmdline, env)
  461. return rv
  462. self["SPAWN"] = mySpawn
  463. def no_verbose(sys, env):
  464. colors = {}
  465. # Colors are disabled in non-TTY environments such as pipes. This means
  466. # that if output is redirected to a file, it will not contain color codes
  467. if sys.stdout.isatty():
  468. colors["blue"] = "\033[0;94m"
  469. colors["bold_blue"] = "\033[1;94m"
  470. colors["reset"] = "\033[0m"
  471. else:
  472. colors["blue"] = ""
  473. colors["bold_blue"] = ""
  474. colors["reset"] = ""
  475. # There is a space before "..." to ensure that source file names can be
  476. # Ctrl + clicked in the VS Code terminal.
  477. compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  478. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  479. )
  480. java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(
  481. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  482. )
  483. compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(
  484. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  485. )
  486. link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(
  487. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  488. )
  489. link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(
  490. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  491. )
  492. ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(
  493. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  494. )
  495. link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(
  496. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  497. )
  498. java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(
  499. colors["blue"], colors["bold_blue"], colors["blue"], colors["reset"]
  500. )
  501. env.Append(CXXCOMSTR=[compile_source_message])
  502. env.Append(CCCOMSTR=[compile_source_message])
  503. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  504. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  505. env.Append(ARCOMSTR=[link_library_message])
  506. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  507. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  508. env.Append(LINKCOMSTR=[link_program_message])
  509. env.Append(JARCOMSTR=[java_library_message])
  510. env.Append(JAVACCOMSTR=[java_compile_source_message])
  511. def detect_visual_c_compiler_version(tools_env):
  512. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  513. # (see the SCons documentation for more information on what it does)...
  514. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  515. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  516. # the proper vc version that will be called
  517. # 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.).
  518. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  519. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  520. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  521. # the following string values:
  522. # "" Compiler not detected
  523. # "amd64" Native 64 bit compiler
  524. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  525. # "x86" Native 32 bit compiler
  526. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  527. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  528. # and similar architectures/compilers
  529. # Set chosen compiler to "not detected"
  530. vc_chosen_compiler_index = -1
  531. vc_chosen_compiler_str = ""
  532. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  533. if "VCINSTALLDIR" in tools_env:
  534. # print("Checking VCINSTALLDIR")
  535. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  536. # First test if amd64 and amd64_x86 compilers are present in the path
  537. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  538. if vc_amd64_compiler_detection_index > -1:
  539. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  540. vc_chosen_compiler_str = "amd64"
  541. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  542. if vc_amd64_x86_compiler_detection_index > -1 and (
  543. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  544. ):
  545. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  546. vc_chosen_compiler_str = "amd64_x86"
  547. # Now check the 32 bit compilers
  548. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  549. if vc_x86_compiler_detection_index > -1 and (
  550. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  551. ):
  552. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  553. vc_chosen_compiler_str = "x86"
  554. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\x86_amd64;")
  555. if vc_x86_amd64_compiler_detection_index > -1 and (
  556. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  557. ):
  558. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  559. vc_chosen_compiler_str = "x86_amd64"
  560. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  561. if "VCTOOLSINSTALLDIR" in tools_env:
  562. # Newer versions have a different path available
  563. vc_amd64_compiler_detection_index = (
  564. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;")
  565. )
  566. if vc_amd64_compiler_detection_index > -1:
  567. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  568. vc_chosen_compiler_str = "amd64"
  569. vc_amd64_x86_compiler_detection_index = (
  570. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;")
  571. )
  572. if vc_amd64_x86_compiler_detection_index > -1 and (
  573. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index
  574. ):
  575. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  576. vc_chosen_compiler_str = "amd64_x86"
  577. vc_x86_compiler_detection_index = (
  578. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;")
  579. )
  580. if vc_x86_compiler_detection_index > -1 and (
  581. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index
  582. ):
  583. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  584. vc_chosen_compiler_str = "x86"
  585. vc_x86_amd64_compiler_detection_index = (
  586. tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;")
  587. )
  588. if vc_x86_amd64_compiler_detection_index > -1 and (
  589. vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index
  590. ):
  591. vc_chosen_compiler_str = "x86_amd64"
  592. return vc_chosen_compiler_str
  593. def find_visual_c_batch_file(env):
  594. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file, find_vc_pdir
  595. # Syntax changed in SCons 4.4.0.
  596. from SCons import __version__ as scons_raw_version
  597. scons_ver = env._get_major_minor_revision(scons_raw_version)
  598. msvc_version = get_default_version(env)
  599. if scons_ver >= (4, 4, 0):
  600. (host_platform, target_platform, _) = get_host_target(env, msvc_version)
  601. else:
  602. (host_platform, target_platform, _) = get_host_target(env)
  603. if scons_ver < (4, 6, 0):
  604. return find_batch_file(env, msvc_version, host_platform, target_platform)[0]
  605. # Scons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first,
  606. # then pass that as the last param instead of env as the first param as before.
  607. # We should investigate if we can avoid relying on SCons internals here.
  608. product_dir = find_vc_pdir(env, msvc_version)
  609. return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[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)