methods.py 46 KB

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