methods.py 50 KB

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