SConstruct 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. #!/usr/bin/env python
  2. EnsureSConsVersion(0, 98, 1)
  3. import string
  4. import os
  5. import os.path
  6. import glob
  7. import sys
  8. import methods
  9. import gles_builders
  10. from platform_methods import run_in_subprocess
  11. # scan possible build platforms
  12. platform_list = [] # list of platforms
  13. platform_opts = {} # options for each platform
  14. platform_flags = {} # flags for each platform
  15. active_platforms = []
  16. active_platform_ids = []
  17. platform_exporters = []
  18. platform_apis = []
  19. for x in sorted(glob.glob("platform/*")):
  20. if (not os.path.isdir(x) or not os.path.exists(x + "/detect.py")):
  21. continue
  22. tmppath = "./" + x
  23. sys.path.append(tmppath)
  24. import detect
  25. if (os.path.exists(x + "/export/export.cpp")):
  26. platform_exporters.append(x[9:])
  27. if (os.path.exists(x + "/api/api.cpp")):
  28. platform_apis.append(x[9:])
  29. if (detect.is_active()):
  30. active_platforms.append(detect.get_name())
  31. active_platform_ids.append(x)
  32. if (detect.can_build()):
  33. x = x.replace("platform/", "") # rest of world
  34. x = x.replace("platform\\", "") # win32
  35. platform_list += [x]
  36. platform_opts[x] = detect.get_opts()
  37. platform_flags[x] = detect.get_flags()
  38. sys.path.remove(tmppath)
  39. sys.modules.pop('detect')
  40. module_list = methods.detect_modules()
  41. methods.save_active_platforms(active_platforms, active_platform_ids)
  42. custom_tools = ['default']
  43. platform_arg = ARGUMENTS.get("platform", ARGUMENTS.get("p", False))
  44. if os.name == "nt" and (platform_arg == "android" or ARGUMENTS.get("use_mingw", False)):
  45. custom_tools = ['mingw']
  46. elif platform_arg == 'javascript':
  47. # Use generic POSIX build toolchain for Emscripten.
  48. custom_tools = ['cc', 'c++', 'ar', 'link', 'textfile', 'zip']
  49. env_base = Environment(tools=custom_tools)
  50. if 'TERM' in os.environ:
  51. env_base['ENV']['TERM'] = os.environ['TERM']
  52. env_base.AppendENVPath('PATH', os.getenv('PATH'))
  53. env_base.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH'))
  54. env_base.android_maven_repos = []
  55. env_base.android_flat_dirs = []
  56. env_base.android_dependencies = []
  57. env_base.android_gradle_plugins = []
  58. env_base.android_gradle_classpath = []
  59. env_base.android_java_dirs = []
  60. env_base.android_res_dirs = []
  61. env_base.android_asset_dirs = []
  62. env_base.android_aidl_dirs = []
  63. env_base.android_jni_dirs = []
  64. env_base.android_default_config = []
  65. env_base.android_manifest_chunk = ""
  66. env_base.android_permission_chunk = ""
  67. env_base.android_appattributes_chunk = ""
  68. env_base.disabled_modules = []
  69. env_base.use_ptrcall = False
  70. env_base.split_drivers = False
  71. env_base.split_modules = False
  72. env_base.module_version_string = ""
  73. env_base.msvc = False
  74. # To decide whether to rebuild a file, use the MD5 sum only if the timestamp has changed.
  75. # http://scons.org/doc/production/HTML/scons-user/ch06.html#idm139837621851792
  76. env_base.Decider('MD5-timestamp')
  77. # Use cached implicit dependencies by default. Can be overridden by specifying `--implicit-deps-changed` in the command line.
  78. # http://scons.org/doc/production/HTML/scons-user/ch06s04.html
  79. env_base.SetOption('implicit_cache', 1)
  80. env_base.__class__.android_add_maven_repository = methods.android_add_maven_repository
  81. env_base.__class__.android_add_flat_dir = methods.android_add_flat_dir
  82. env_base.__class__.android_add_dependency = methods.android_add_dependency
  83. env_base.__class__.android_add_java_dir = methods.android_add_java_dir
  84. env_base.__class__.android_add_res_dir = methods.android_add_res_dir
  85. env_base.__class__.android_add_asset_dir = methods.android_add_asset_dir
  86. env_base.__class__.android_add_aidl_dir = methods.android_add_aidl_dir
  87. env_base.__class__.android_add_jni_dir = methods.android_add_jni_dir
  88. env_base.__class__.android_add_default_config = methods.android_add_default_config
  89. env_base.__class__.android_add_to_manifest = methods.android_add_to_manifest
  90. env_base.__class__.android_add_to_permissions = methods.android_add_to_permissions
  91. env_base.__class__.android_add_to_attributes = methods.android_add_to_attributes
  92. env_base.__class__.android_add_gradle_plugin = methods.android_add_gradle_plugin
  93. env_base.__class__.android_add_gradle_classpath = methods.android_add_gradle_classpath
  94. env_base.__class__.disable_module = methods.disable_module
  95. env_base.__class__.add_module_version_string = methods.add_module_version_string
  96. env_base.__class__.add_source_files = methods.add_source_files
  97. env_base.__class__.use_windows_spawn_fix = methods.use_windows_spawn_fix
  98. env_base.__class__.split_lib = methods.split_lib
  99. env_base.__class__.add_shared_library = methods.add_shared_library
  100. env_base.__class__.add_library = methods.add_library
  101. env_base.__class__.add_program = methods.add_program
  102. env_base.__class__.CommandNoCache = methods.CommandNoCache
  103. env_base.__class__.disable_warnings = methods.disable_warnings
  104. env_base["x86_libtheora_opt_gcc"] = False
  105. env_base["x86_libtheora_opt_vc"] = False
  106. # Build options
  107. customs = ['custom.py']
  108. profile = ARGUMENTS.get("profile", False)
  109. if profile:
  110. import os.path
  111. if os.path.isfile(profile):
  112. customs.append(profile)
  113. elif os.path.isfile(profile + ".py"):
  114. customs.append(profile + ".py")
  115. opts = Variables(customs, ARGUMENTS)
  116. # Target build options
  117. opts.Add('arch', "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", '')
  118. opts.Add(EnumVariable('bits', "Target platform bits", 'default', ('default', '32', '64')))
  119. opts.Add('p', "Platform (alias for 'platform')", '')
  120. opts.Add('platform', "Target platform (%s)" % ('|'.join(platform_list), ), '')
  121. opts.Add(EnumVariable('target', "Compilation target", 'debug', ('debug', 'release_debug', 'release')))
  122. opts.Add(EnumVariable('optimize', "Optimization type", 'speed', ('speed', 'size')))
  123. opts.Add(BoolVariable('tools', "Build the tools (a.k.a. the Godot editor)", True))
  124. opts.Add(BoolVariable('use_lto', 'Use link-time optimization', False))
  125. # Components
  126. opts.Add(BoolVariable('deprecated', "Enable deprecated features", True))
  127. opts.Add(BoolVariable('gdscript', "Enable GDScript support", True))
  128. opts.Add(BoolVariable('minizip', "Enable ZIP archive support using minizip", True))
  129. opts.Add(BoolVariable('xaudio2', "Enable the XAudio2 audio driver", False))
  130. # Advanced options
  131. opts.Add(BoolVariable('verbose', "Enable verbose output for the compilation", False))
  132. opts.Add(BoolVariable('progress', "Show a progress indicator during compilation", True))
  133. opts.Add(EnumVariable('warnings', "Set the level of warnings emitted during compilation", 'all', ('extra', 'all', 'moderate', 'no')))
  134. opts.Add(BoolVariable('werror', "Treat compiler warnings as errors. Depends on the level of warnings set with 'warnings'", False))
  135. opts.Add(BoolVariable('dev', "If yes, alias for verbose=yes warnings=all", False))
  136. opts.Add('extra_suffix', "Custom extra suffix added to the base filename of all generated binary files", '')
  137. opts.Add(BoolVariable('vsproj', "Generate a Visual Studio solution", False))
  138. opts.Add(EnumVariable('macports_clang', "Build using Clang from MacPorts", 'no', ('no', '5.0', 'devel')))
  139. opts.Add(BoolVariable('disable_3d', "Disable 3D nodes for a smaller executable", False))
  140. opts.Add(BoolVariable('disable_advanced_gui', "Disable advanced GUI nodes and behaviors", False))
  141. opts.Add(BoolVariable('no_editor_splash', "Don't use the custom splash screen for the editor", False))
  142. opts.Add('system_certs_path', "Use this path as SSL certificates default for editor (for package maintainers)", '')
  143. # Thirdparty libraries
  144. opts.Add(BoolVariable('builtin_bullet', "Use the built-in Bullet library", True))
  145. opts.Add(BoolVariable('builtin_certs', "Bundle default SSL certificates to be used if you don't specify an override in the project settings", True))
  146. opts.Add(BoolVariable('builtin_enet', "Use the built-in ENet library", True))
  147. opts.Add(BoolVariable('builtin_freetype', "Use the built-in FreeType library", True))
  148. opts.Add(BoolVariable('builtin_libogg', "Use the built-in libogg library", True))
  149. opts.Add(BoolVariable('builtin_libpng', "Use the built-in libpng library", True))
  150. opts.Add(BoolVariable('builtin_libtheora', "Use the built-in libtheora library", True))
  151. opts.Add(BoolVariable('builtin_libvorbis', "Use the built-in libvorbis library", True))
  152. opts.Add(BoolVariable('builtin_libvpx', "Use the built-in libvpx library", True))
  153. opts.Add(BoolVariable('builtin_libwebp', "Use the built-in libwebp library", True))
  154. opts.Add(BoolVariable('builtin_libwebsockets', "Use the built-in libwebsockets library", True))
  155. opts.Add(BoolVariable('builtin_mbedtls', "Use the built-in mbedTLS library", True))
  156. opts.Add(BoolVariable('builtin_miniupnpc', "Use the built-in miniupnpc library", True))
  157. opts.Add(BoolVariable('builtin_opus', "Use the built-in Opus library", True))
  158. opts.Add(BoolVariable('builtin_pcre2', "Use the built-in PCRE2 library)", True))
  159. opts.Add(BoolVariable('builtin_recast', "Use the built-in Recast library", True))
  160. opts.Add(BoolVariable('builtin_squish', "Use the built-in squish library", True))
  161. opts.Add(BoolVariable('builtin_thekla_atlas', "Use the built-in thekla_altas library", True))
  162. opts.Add(BoolVariable('builtin_xatlas', "Use the built-in xatlas library", True))
  163. opts.Add(BoolVariable('builtin_zlib', "Use the built-in zlib library", True))
  164. opts.Add(BoolVariable('builtin_zstd', "Use the built-in Zstd library", True))
  165. # Compilation environment setup
  166. opts.Add("CXX", "C++ compiler")
  167. opts.Add("CC", "C compiler")
  168. opts.Add("LINK", "Linker")
  169. opts.Add("CCFLAGS", "Custom flags for both the C and C++ compilers")
  170. opts.Add("CXXFLAGS", "Custom flags for the C++ compiler")
  171. opts.Add("CFLAGS", "Custom flags for the C compiler")
  172. opts.Add("LINKFLAGS", "Custom flags for the linker")
  173. # add platform specific options
  174. for k in platform_opts.keys():
  175. opt_list = platform_opts[k]
  176. for o in opt_list:
  177. opts.Add(o)
  178. for x in module_list:
  179. module_enabled = True
  180. tmppath = "./modules/" + x
  181. sys.path.append(tmppath)
  182. import config
  183. enabled_attr = getattr(config, "is_enabled", None)
  184. if (callable(enabled_attr) and not config.is_enabled()):
  185. module_enabled = False
  186. sys.path.remove(tmppath)
  187. sys.modules.pop('config')
  188. opts.Add(BoolVariable('module_' + x + '_enabled', "Enable module '%s'" % (x, ), module_enabled))
  189. opts.Update(env_base) # update environment
  190. Help(opts.GenerateHelpText(env_base)) # generate help
  191. # add default include paths
  192. env_base.Append(CPPPATH=['#editor', '#'])
  193. # configure ENV for platform
  194. env_base.platform_exporters = platform_exporters
  195. env_base.platform_apis = platform_apis
  196. if (env_base['target'] == 'debug'):
  197. env_base.Append(CPPDEFINES=['DEBUG_MEMORY_ALLOC','DISABLE_FORCED_INLINE'])
  198. if (env_base['no_editor_splash']):
  199. env_base.Append(CPPDEFINES=['NO_EDITOR_SPLASH'])
  200. if not env_base['deprecated']:
  201. env_base.Append(CPPDEFINES=['DISABLE_DEPRECATED'])
  202. env_base.platforms = {}
  203. selected_platform = ""
  204. if env_base['platform'] != "":
  205. selected_platform = env_base['platform']
  206. elif env_base['p'] != "":
  207. selected_platform = env_base['p']
  208. env_base["platform"] = selected_platform
  209. if selected_platform in platform_list:
  210. sys.path.append("./platform/" + selected_platform)
  211. import detect
  212. if "create" in dir(detect):
  213. env = detect.create(env_base)
  214. else:
  215. env = env_base.Clone()
  216. if env['dev']:
  217. env["warnings"] = "all"
  218. env['verbose'] = True
  219. if env['vsproj']:
  220. env.vs_incs = []
  221. env.vs_srcs = []
  222. def AddToVSProject(sources):
  223. for x in sources:
  224. if type(x) == type(""):
  225. fname = env.File(x).path
  226. else:
  227. fname = env.File(x)[0].path
  228. pieces = fname.split(".")
  229. if len(pieces) > 0:
  230. basename = pieces[0]
  231. basename = basename.replace('\\\\', '/')
  232. if os.path.isfile(basename + ".h"):
  233. env.vs_incs = env.vs_incs + [basename + ".h"]
  234. elif os.path.isfile(basename + ".hpp"):
  235. env.vs_incs = env.vs_incs + [basename + ".hpp"]
  236. if os.path.isfile(basename + ".c"):
  237. env.vs_srcs = env.vs_srcs + [basename + ".c"]
  238. elif os.path.isfile(basename + ".cpp"):
  239. env.vs_srcs = env.vs_srcs + [basename + ".cpp"]
  240. env.AddToVSProject = AddToVSProject
  241. env.extra_suffix = ""
  242. if env["extra_suffix"] != '':
  243. env.extra_suffix += '.' + env["extra_suffix"]
  244. CCFLAGS = env.get('CCFLAGS', '')
  245. env['CCFLAGS'] = ''
  246. env.Append(CCFLAGS=str(CCFLAGS).split())
  247. CFLAGS = env.get('CFLAGS', '')
  248. env['CFLAGS'] = ''
  249. env.Append(CFLAGS=str(CFLAGS).split())
  250. LINKFLAGS = env.get('LINKFLAGS', '')
  251. env['LINKFLAGS'] = ''
  252. env.Append(LINKFLAGS=str(LINKFLAGS).split())
  253. flag_list = platform_flags[selected_platform]
  254. for f in flag_list:
  255. if not (f[0] in ARGUMENTS): # allow command line to override platform flags
  256. env[f[0]] = f[1]
  257. # must happen after the flags, so when flags are used by configure, stuff happens (ie, ssl on x11)
  258. detect.configure(env)
  259. # Configure compiler warnings
  260. if env.msvc:
  261. # Truncations, narrowing conversions, signed/unsigned comparisons...
  262. disable_nonessential_warnings = ['/wd4267', '/wd4244', '/wd4305', '/wd4018', '/wd4800']
  263. if (env["warnings"] == 'extra'):
  264. env.Append(CCFLAGS=['/Wall']) # Implies /W4
  265. elif (env["warnings"] == 'all'):
  266. env.Append(CCFLAGS=['/W3'] + disable_nonessential_warnings)
  267. elif (env["warnings"] == 'moderate'):
  268. env.Append(CCFLAGS=['/W2'] + disable_nonessential_warnings)
  269. else: # 'no'
  270. env.Append(CCFLAGS=['/w'])
  271. # Set exception handling model to avoid warnings caused by Windows system headers.
  272. env.Append(CCFLAGS=['/EHsc'])
  273. if (env["werror"]):
  274. env.Append(CCFLAGS=['/WX'])
  275. else: # Rest of the world
  276. disable_nonessential_warnings = ['-Wno-sign-compare']
  277. if (env["warnings"] == 'extra'):
  278. env.Append(CCFLAGS=['-Wall', '-Wextra'])
  279. elif (env["warnings"] == 'all'):
  280. env.Append(CCFLAGS=['-Wall'] + disable_nonessential_warnings)
  281. elif (env["warnings"] == 'moderate'):
  282. env.Append(CCFLAGS=['-Wall', '-Wno-unused'] + disable_nonessential_warnings)
  283. else: # 'no'
  284. env.Append(CCFLAGS=['-w'])
  285. if (env["werror"]):
  286. env.Append(CCFLAGS=['-Werror'])
  287. else: # always enable those errors
  288. env.Append(CCFLAGS=['-Werror=return-type'])
  289. if (hasattr(detect, 'get_program_suffix')):
  290. suffix = "." + detect.get_program_suffix()
  291. else:
  292. suffix = "." + selected_platform
  293. if (env["target"] == "release"):
  294. if env["tools"]:
  295. print("Tools can only be built with targets 'debug' and 'release_debug'.")
  296. sys.exit(255)
  297. suffix += ".opt"
  298. env.Append(CPPDEFINES=['NDEBUG'])
  299. elif (env["target"] == "release_debug"):
  300. if env["tools"]:
  301. suffix += ".opt.tools"
  302. else:
  303. suffix += ".opt.debug"
  304. else:
  305. if env["tools"]:
  306. suffix += ".tools"
  307. else:
  308. suffix += ".debug"
  309. if env["arch"] != "":
  310. suffix += "." + env["arch"]
  311. elif (env["bits"] == "32"):
  312. suffix += ".32"
  313. elif (env["bits"] == "64"):
  314. suffix += ".64"
  315. suffix += env.extra_suffix
  316. sys.path.remove("./platform/" + selected_platform)
  317. sys.modules.pop('detect')
  318. env.module_list = []
  319. env.doc_class_path = {}
  320. for x in module_list:
  321. if not env['module_' + x + '_enabled']:
  322. continue
  323. tmppath = "./modules/" + x
  324. sys.path.append(tmppath)
  325. env.current_module = x
  326. import config
  327. # can_build changed number of arguments between 3.0 (1) and 3.1 (2),
  328. # so try both to preserve compatibility for 3.0 modules
  329. can_build = False
  330. try:
  331. can_build = config.can_build(env, selected_platform)
  332. except TypeError:
  333. print("Warning: module '%s' uses a deprecated `can_build` "
  334. "signature in its config.py file, it should be "
  335. "`can_build(env, platform)`." % x)
  336. can_build = config.can_build(selected_platform)
  337. if (can_build):
  338. config.configure(env)
  339. env.module_list.append(x)
  340. try:
  341. doc_classes = config.get_doc_classes()
  342. doc_path = config.get_doc_path()
  343. for c in doc_classes:
  344. env.doc_class_path[c] = "modules/" + x + "/" + doc_path
  345. except:
  346. pass
  347. sys.path.remove(tmppath)
  348. sys.modules.pop('config')
  349. methods.update_version(env.module_version_string)
  350. env["PROGSUFFIX"] = suffix + env.module_version_string + env["PROGSUFFIX"]
  351. env["OBJSUFFIX"] = suffix + env["OBJSUFFIX"]
  352. # (SH)LIBSUFFIX will be used for our own built libraries
  353. # LIBSUFFIXES contains LIBSUFFIX and SHLIBSUFFIX by default,
  354. # so we need to append the default suffixes to keep the ability
  355. # to link against thirdparty libraries (.a, .so, .lib, etc.).
  356. if os.name == "nt":
  357. # On Windows, only static libraries and import libraries can be
  358. # statically linked - both using .lib extension
  359. env["LIBSUFFIXES"] += [env["LIBSUFFIX"]]
  360. else:
  361. env["LIBSUFFIXES"] += [env["LIBSUFFIX"], env["SHLIBSUFFIX"]]
  362. env["LIBSUFFIX"] = suffix + env["LIBSUFFIX"]
  363. env["SHLIBSUFFIX"] = suffix + env["SHLIBSUFFIX"]
  364. if (env.use_ptrcall):
  365. env.Append(CPPDEFINES=['PTRCALL_ENABLED'])
  366. if env['tools']:
  367. env.Append(CPPDEFINES=['TOOLS_ENABLED'])
  368. if env['disable_3d']:
  369. if env['tools']:
  370. print("Build option 'disable_3d=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  371. sys.exit(255)
  372. else:
  373. env.Append(CPPDEFINES=['_3D_DISABLED'])
  374. if env['gdscript']:
  375. env.Append(CPPDEFINES=['GDSCRIPT_ENABLED'])
  376. if env['disable_advanced_gui']:
  377. if env['tools']:
  378. print("Build option 'disable_advanced_gui=yes' cannot be used with 'tools=yes' (editor), only with 'tools=no' (export template).")
  379. sys.exit(255)
  380. else:
  381. env.Append(CPPDEFINES=['ADVANCED_GUI_DISABLED'])
  382. if env['minizip']:
  383. env.Append(CPPDEFINES=['MINIZIP_ENABLED'])
  384. if not env['verbose']:
  385. methods.no_verbose(sys, env)
  386. if (not env["platform"] == "server"): # FIXME: detect GLES3
  387. env.Append(BUILDERS = { 'GLES3_GLSL' : env.Builder(action=run_in_subprocess(gles_builders.build_gles3_headers), suffix='glsl.gen.h', src_suffix='.glsl')})
  388. env.Append(BUILDERS = { 'GLES2_GLSL' : env.Builder(action=run_in_subprocess(gles_builders.build_gles2_headers), suffix='glsl.gen.h', src_suffix='.glsl')})
  389. scons_cache_path = os.environ.get("SCONS_CACHE")
  390. if scons_cache_path != None:
  391. CacheDir(scons_cache_path)
  392. print("Scons cache enabled... (path: '" + scons_cache_path + "')")
  393. Export('env')
  394. # build subdirs, the build order is dependent on link order.
  395. SConscript("core/SCsub")
  396. SConscript("servers/SCsub")
  397. SConscript("scene/SCsub")
  398. SConscript("editor/SCsub")
  399. SConscript("drivers/SCsub")
  400. SConscript("platform/SCsub")
  401. SConscript("modules/SCsub")
  402. SConscript("main/SCsub")
  403. SConscript("platform/" + selected_platform + "/SCsub") # build selected platform
  404. # Microsoft Visual Studio Project Generation
  405. if env['vsproj']:
  406. env['CPPPATH'] = [Dir(path) for path in env['CPPPATH']]
  407. methods.generate_vs_project(env, GetOption("num_jobs"))
  408. methods.generate_cpp_hint_file("cpp.hint")
  409. # Check for the existence of headers
  410. conf = Configure(env)
  411. if ("check_c_headers" in env):
  412. for header in env["check_c_headers"]:
  413. if (conf.CheckCHeader(header[0])):
  414. env.AppendUnique(CPPDEFINES=[header[1]])
  415. else:
  416. print("No valid target platform selected.")
  417. print("The following platforms were detected:")
  418. for x in platform_list:
  419. print("\t" + x)
  420. print("\nPlease run SCons again with the argument: platform=<string>")
  421. # The following only makes sense when the env is defined, and assumes it is
  422. if 'env' in locals():
  423. screen = sys.stdout
  424. # Progress reporting is not available in non-TTY environments since it
  425. # messes with the output (for example, when writing to a file)
  426. show_progress = (env['progress'] and sys.stdout.isatty())
  427. node_count = 0
  428. node_count_max = 0
  429. node_count_interval = 1
  430. node_count_fname = str(env.Dir('#')) + '/.scons_node_count'
  431. import time, math
  432. class cache_progress:
  433. # The default is 1 GB cache and 12 hours half life
  434. def __init__(self, path = None, limit = 1073741824, half_life = 43200):
  435. self.path = path
  436. self.limit = limit
  437. self.exponent_scale = math.log(2) / half_life
  438. if env['verbose'] and path != None:
  439. screen.write('Current cache limit is ' + self.convert_size(limit) + ' (used: ' + self.convert_size(self.get_size(path)) + ')\n')
  440. self.delete(self.file_list())
  441. def __call__(self, node, *args, **kw):
  442. global node_count, node_count_max, node_count_interval, node_count_fname, show_progress
  443. if show_progress:
  444. # Print the progress percentage
  445. node_count += node_count_interval
  446. if (node_count_max > 0 and node_count <= node_count_max):
  447. screen.write('\r[%3d%%] ' % (node_count * 100 / node_count_max))
  448. screen.flush()
  449. elif (node_count_max > 0 and node_count > node_count_max):
  450. screen.write('\r[100%] ')
  451. screen.flush()
  452. else:
  453. screen.write('\r[Initial build] ')
  454. screen.flush()
  455. def delete(self, files):
  456. if len(files) == 0:
  457. return
  458. if env['verbose']:
  459. # Utter something
  460. screen.write('\rPurging %d %s from cache...\n' % (len(files), len(files) > 1 and 'files' or 'file'))
  461. [os.remove(f) for f in files]
  462. def file_list(self):
  463. if self.path is None:
  464. # Nothing to do
  465. return []
  466. # Gather a list of (filename, (size, atime)) within the
  467. # cache directory
  468. file_stat = [(x, os.stat(x)[6:8]) for x in glob.glob(os.path.join(self.path, '*', '*'))]
  469. if file_stat == []:
  470. # Nothing to do
  471. return []
  472. # Weight the cache files by size (assumed to be roughly
  473. # proportional to the recompilation time) times an exponential
  474. # decay since the ctime, and return a list with the entries
  475. # (filename, size, weight).
  476. current_time = time.time()
  477. file_stat = [(x[0], x[1][0], (current_time - x[1][1])) for x in file_stat]
  478. # Sort by the most resently accessed files (most sensible to keep) first
  479. file_stat.sort(key=lambda x: x[2])
  480. # Search for the first entry where the storage limit is
  481. # reached
  482. sum, mark = 0, None
  483. for i,x in enumerate(file_stat):
  484. sum += x[1]
  485. if sum > self.limit:
  486. mark = i
  487. break
  488. if mark is None:
  489. return []
  490. else:
  491. return [x[0] for x in file_stat[mark:]]
  492. def convert_size(self, size_bytes):
  493. if size_bytes == 0:
  494. return "0 bytes"
  495. size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
  496. i = int(math.floor(math.log(size_bytes, 1024)))
  497. p = math.pow(1024, i)
  498. s = round(size_bytes / p, 2)
  499. return "%s %s" % (int(s) if i == 0 else s, size_name[i])
  500. def get_size(self, start_path = '.'):
  501. total_size = 0
  502. for dirpath, dirnames, filenames in os.walk(start_path):
  503. for f in filenames:
  504. fp = os.path.join(dirpath, f)
  505. total_size += os.path.getsize(fp)
  506. return total_size
  507. def progress_finish(target, source, env):
  508. global node_count, progressor
  509. with open(node_count_fname, 'w') as f:
  510. f.write('%d\n' % node_count)
  511. progressor.delete(progressor.file_list())
  512. try:
  513. with open(node_count_fname) as f:
  514. node_count_max = int(f.readline())
  515. except:
  516. pass
  517. cache_directory = os.environ.get("SCONS_CACHE")
  518. # Simple cache pruning, attached to SCons' progress callback. Trim the
  519. # cache directory to a size not larger than cache_limit.
  520. cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", 1024)) * 1024 * 1024
  521. progressor = cache_progress(cache_directory, cache_limit)
  522. Progress(progressor, interval = node_count_interval)
  523. progress_finish_command = Command('progress_finish', [], progress_finish)
  524. AlwaysBuild(progress_finish_command)