methods.py 45 KB

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