methods.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. import os
  2. import os.path
  3. import re
  4. import glob
  5. import subprocess
  6. from compat import iteritems, isbasestring, decode_utf8
  7. def add_source_files(self, sources, files, warn_duplicates=True):
  8. # Convert string to list of absolute paths (including expanding wildcard)
  9. if isbasestring(files):
  10. # Keep SCons project-absolute path as they are (no wildcard support)
  11. if files.startswith('#'):
  12. if '*' in files:
  13. print("ERROR: Wildcards can't be expanded in SCons project-absolute path: '{}'".format(files))
  14. return
  15. files = [files]
  16. else:
  17. dir_path = self.Dir('.').abspath
  18. files = sorted(glob.glob(dir_path + "/" + files))
  19. # Add each path as compiled Object following environment (self) configuration
  20. for path in files:
  21. obj = self.Object(path)
  22. if obj in sources:
  23. if warn_duplicates:
  24. print("WARNING: Object \"{}\" already included in environment sources.".format(obj))
  25. else:
  26. continue
  27. sources.append(obj)
  28. def disable_warnings(self):
  29. # 'self' is the environment
  30. if self.msvc:
  31. # We have to remove existing warning level defines before appending /w,
  32. # otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
  33. warn_flags = ['/Wall', '/W4', '/W3', '/W2', '/W1', '/WX']
  34. self.Append(CCFLAGS=['/w'])
  35. self.Append(CFLAGS=['/w'])
  36. self.Append(CXXFLAGS=['/w'])
  37. self['CCFLAGS'] = [x for x in self['CCFLAGS'] if not x in warn_flags]
  38. self['CFLAGS'] = [x for x in self['CFLAGS'] if not x in warn_flags]
  39. self['CXXFLAGS'] = [x for x in self['CXXFLAGS'] if not x in warn_flags]
  40. else:
  41. self.Append(CCFLAGS=['-w'])
  42. self.Append(CFLAGS=['-w'])
  43. self.Append(CXXFLAGS=['-w'])
  44. def add_module_version_string(self,s):
  45. self.module_version_string += "." + s
  46. def update_version(module_version_string=""):
  47. build_name = "custom_build"
  48. if os.getenv("BUILD_NAME") != None:
  49. build_name = os.getenv("BUILD_NAME")
  50. print("Using custom build name: " + build_name)
  51. import version
  52. # NOTE: It is safe to generate this file here, since this is still executed serially
  53. f = open("core/version_generated.gen.h", "w")
  54. f.write("#define VERSION_SHORT_NAME \"" + str(version.short_name) + "\"\n")
  55. f.write("#define VERSION_NAME \"" + str(version.name) + "\"\n")
  56. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  57. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  58. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  59. f.write("#define VERSION_STATUS \"" + str(version.status) + "\"\n")
  60. f.write("#define VERSION_BUILD \"" + str(build_name) + "\"\n")
  61. f.write("#define VERSION_MODULE_CONFIG \"" + str(version.module_config) + module_version_string + "\"\n")
  62. f.write("#define VERSION_YEAR " + str(version.year) + "\n")
  63. f.write("#define VERSION_WEBSITE \"" + str(version.website) + "\"\n")
  64. f.close()
  65. # NOTE: It is safe to generate this file here, since this is still executed serially
  66. fhash = open("core/version_hash.gen.h", "w")
  67. githash = ""
  68. gitfolder = ".git"
  69. if os.path.isfile(".git"):
  70. module_folder = open(".git", "r").readline().strip()
  71. if module_folder.startswith("gitdir: "):
  72. gitfolder = module_folder[8:]
  73. if os.path.isfile(os.path.join(gitfolder, "HEAD")):
  74. head = open(os.path.join(gitfolder, "HEAD"), "r").readline().strip()
  75. if head.startswith("ref: "):
  76. head = os.path.join(gitfolder, head[5:])
  77. if os.path.isfile(head):
  78. githash = open(head, "r").readline().strip()
  79. else:
  80. githash = head
  81. fhash.write("#define VERSION_HASH \"" + githash + "\"")
  82. fhash.close()
  83. def parse_cg_file(fname, uniforms, sizes, conditionals):
  84. fs = open(fname, "r")
  85. line = fs.readline()
  86. while line:
  87. if re.match(r"^\s*uniform", line):
  88. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  89. type = res.groups(1)
  90. name = res.groups(2)
  91. uniforms.append(name)
  92. if type.find("texobj") != -1:
  93. sizes.append(1)
  94. else:
  95. t = re.match(r"float(\d)x(\d)", type)
  96. if t:
  97. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  98. else:
  99. t = re.match(r"float(\d)", type)
  100. sizes.append(int(t.groups(1)))
  101. if line.find("[branch]") != -1:
  102. conditionals.append(name)
  103. line = fs.readline()
  104. fs.close()
  105. def detect_modules():
  106. module_list = []
  107. includes_cpp = ""
  108. register_cpp = ""
  109. unregister_cpp = ""
  110. preregister_cpp = ""
  111. files = glob.glob("modules/*")
  112. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  113. for x in files:
  114. if not os.path.isdir(x):
  115. continue
  116. if not os.path.exists(x + "/config.py"):
  117. continue
  118. x = x.replace("modules/", "") # rest of world
  119. x = x.replace("modules\\", "") # win32
  120. module_list.append(x)
  121. try:
  122. with open("modules/" + x + "/register_types.h"):
  123. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  124. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  125. register_cpp += '\tregister_' + x + '_types();\n'
  126. register_cpp += '#endif\n'
  127. preregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  128. preregister_cpp += '#ifdef MODULE_' + x.upper() + '_HAS_PREREGISTER\n'
  129. preregister_cpp += '\tpreregister_' + x + '_types();\n'
  130. preregister_cpp += '#endif\n'
  131. preregister_cpp += '#endif\n'
  132. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  133. unregister_cpp += '\tunregister_' + x + '_types();\n'
  134. unregister_cpp += '#endif\n'
  135. except IOError:
  136. pass
  137. modules_cpp = """// register_module_types.gen.cpp
  138. /* THIS FILE IS GENERATED DO NOT EDIT */
  139. #include "register_module_types.h"
  140. #include "modules/modules_enabled.gen.h"
  141. %s
  142. void preregister_module_types() {
  143. %s
  144. }
  145. void register_module_types() {
  146. %s
  147. }
  148. void unregister_module_types() {
  149. %s
  150. }
  151. """ % (includes_cpp, preregister_cpp, register_cpp, unregister_cpp)
  152. # NOTE: It is safe to generate this file here, since this is still executed serially
  153. with open("modules/register_module_types.gen.cpp", "w") as f:
  154. f.write(modules_cpp)
  155. return module_list
  156. def win32_spawn(sh, escape, cmd, args, env):
  157. import subprocess
  158. newargs = ' '.join(args[1:])
  159. cmdline = cmd + " " + newargs
  160. startupinfo = subprocess.STARTUPINFO()
  161. for e in env:
  162. if type(env[e]) != type(""):
  163. env[e] = str(env[e])
  164. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  165. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  166. _, err = proc.communicate()
  167. rv = proc.wait()
  168. if rv:
  169. print("=====")
  170. print(err)
  171. print("=====")
  172. return rv
  173. def disable_module(self):
  174. self.disabled_modules.append(self.current_module)
  175. def use_windows_spawn_fix(self, platform=None):
  176. if (os.name != "nt"):
  177. return # not needed, only for windows
  178. # On Windows, due to the limited command line length, when creating a static library
  179. # from a very high number of objects SCons will invoke "ar" once per object file;
  180. # that makes object files with same names to be overwritten so the last wins and
  181. # the library looses symbols defined by overwritten objects.
  182. # By enabling quick append instead of the default mode (replacing), libraries will
  183. # got built correctly regardless the invocation strategy.
  184. # Furthermore, since SCons will rebuild the library from scratch when an object file
  185. # changes, no multiple versions of the same object file will be present.
  186. self.Replace(ARFLAGS='q')
  187. def mySubProcess(cmdline, env):
  188. startupinfo = subprocess.STARTUPINFO()
  189. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  190. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  191. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  192. _, err = proc.communicate()
  193. rv = proc.wait()
  194. if rv:
  195. print("=====")
  196. print(err)
  197. print("=====")
  198. return rv
  199. def mySpawn(sh, escape, cmd, args, env):
  200. newargs = ' '.join(args[1:])
  201. cmdline = cmd + " " + newargs
  202. rv = 0
  203. env = {str(key): str(value) for key, value in iteritems(env)}
  204. if len(cmdline) > 32000 and cmd.endswith("ar"):
  205. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  206. for i in range(3, len(args)):
  207. rv = mySubProcess(cmdline + args[i], env)
  208. if rv:
  209. break
  210. else:
  211. rv = mySubProcess(cmdline, env)
  212. return rv
  213. self['SPAWN'] = mySpawn
  214. def save_active_platforms(apnames, ap):
  215. for x in ap:
  216. names = ['logo']
  217. if os.path.isfile(x + "/run_icon.png"):
  218. names.append('run_icon')
  219. for name in names:
  220. pngf = open(x + "/" + name + ".png", "rb")
  221. b = pngf.read(1)
  222. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  223. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  224. while len(b) == 1:
  225. str += hex(ord(b))
  226. b = pngf.read(1)
  227. if (len(b) == 1):
  228. str += ","
  229. str += "};\n"
  230. pngf.close()
  231. # NOTE: It is safe to generate this file here, since this is still executed serially
  232. wf = x + "/" + name + ".gen.h"
  233. with open(wf, "w") as pngw:
  234. pngw.write(str)
  235. def no_verbose(sys, env):
  236. colors = {}
  237. # Colors are disabled in non-TTY environments such as pipes. This means
  238. # that if output is redirected to a file, it will not contain color codes
  239. if sys.stdout.isatty():
  240. colors['cyan'] = '\033[96m'
  241. colors['purple'] = '\033[95m'
  242. colors['blue'] = '\033[94m'
  243. colors['green'] = '\033[92m'
  244. colors['yellow'] = '\033[93m'
  245. colors['red'] = '\033[91m'
  246. colors['end'] = '\033[0m'
  247. else:
  248. colors['cyan'] = ''
  249. colors['purple'] = ''
  250. colors['blue'] = ''
  251. colors['green'] = ''
  252. colors['yellow'] = ''
  253. colors['red'] = ''
  254. colors['end'] = ''
  255. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  256. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  257. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  258. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  259. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  260. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  261. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  262. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  263. env.Append(CXXCOMSTR=[compile_source_message])
  264. env.Append(CCCOMSTR=[compile_source_message])
  265. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  266. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  267. env.Append(ARCOMSTR=[link_library_message])
  268. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  269. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  270. env.Append(LINKCOMSTR=[link_program_message])
  271. env.Append(JARCOMSTR=[java_library_message])
  272. env.Append(JAVACCOMSTR=[java_compile_source_message])
  273. def detect_visual_c_compiler_version(tools_env):
  274. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  275. # (see the SCons documentation for more information on what it does)...
  276. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  277. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  278. # the proper vc version that will be called
  279. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  280. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  281. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  282. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  283. # the following string values:
  284. # "" Compiler not detected
  285. # "amd64" Native 64 bit compiler
  286. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  287. # "x86" Native 32 bit compiler
  288. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  289. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  290. # and similar architectures/compilers
  291. # Set chosen compiler to "not detected"
  292. vc_chosen_compiler_index = -1
  293. vc_chosen_compiler_str = ""
  294. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  295. if 'VCINSTALLDIR' in tools_env:
  296. # print("Checking VCINSTALLDIR")
  297. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  298. # First test if amd64 and amd64_x86 compilers are present in the path
  299. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  300. if(vc_amd64_compiler_detection_index > -1):
  301. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  302. vc_chosen_compiler_str = "amd64"
  303. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  304. if(vc_amd64_x86_compiler_detection_index > -1
  305. and (vc_chosen_compiler_index == -1
  306. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  307. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  308. vc_chosen_compiler_str = "amd64_x86"
  309. # Now check the 32 bit compilers
  310. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  311. if(vc_x86_compiler_detection_index > -1
  312. and (vc_chosen_compiler_index == -1
  313. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  314. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  315. vc_chosen_compiler_str = "x86"
  316. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  317. if(vc_x86_amd64_compiler_detection_index > -1
  318. and (vc_chosen_compiler_index == -1
  319. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  320. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  321. vc_chosen_compiler_str = "x86_amd64"
  322. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  323. if 'VCTOOLSINSTALLDIR' in tools_env:
  324. # Newer versions have a different path available
  325. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  326. if(vc_amd64_compiler_detection_index > -1):
  327. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  328. vc_chosen_compiler_str = "amd64"
  329. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  330. if(vc_amd64_x86_compiler_detection_index > -1
  331. and (vc_chosen_compiler_index == -1
  332. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  333. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  334. vc_chosen_compiler_str = "amd64_x86"
  335. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  336. if(vc_x86_compiler_detection_index > -1
  337. and (vc_chosen_compiler_index == -1
  338. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  339. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  340. vc_chosen_compiler_str = "x86"
  341. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  342. if(vc_x86_amd64_compiler_detection_index > -1
  343. and (vc_chosen_compiler_index == -1
  344. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  345. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  346. vc_chosen_compiler_str = "x86_amd64"
  347. return vc_chosen_compiler_str
  348. def find_visual_c_batch_file(env):
  349. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  350. version = get_default_version(env)
  351. (host_platform, target_platform, _) = get_host_target(env)
  352. return find_batch_file(env, version, host_platform, target_platform)[0]
  353. def generate_cpp_hint_file(filename):
  354. if os.path.isfile(filename):
  355. # Don't overwrite an existing hint file since the user may have customized it.
  356. pass
  357. else:
  358. try:
  359. with open(filename, "w") as fd:
  360. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  361. except IOError:
  362. print("Could not write cpp.hint file.")
  363. def generate_vs_project(env, num_jobs):
  364. batch_file = find_visual_c_batch_file(env)
  365. if batch_file:
  366. def build_commandline(commands):
  367. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  368. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  369. 'set "tools=yes"',
  370. '(if "$(Configuration)"=="release" (set "tools=no"))',
  371. 'call "' + batch_file + '" !plat!']
  372. result = " ^& ".join(common_build_prefix + [commands])
  373. return result
  374. env.AddToVSProject(env.core_sources)
  375. env.AddToVSProject(env.main_sources)
  376. env.AddToVSProject(env.modules_sources)
  377. env.AddToVSProject(env.scene_sources)
  378. env.AddToVSProject(env.servers_sources)
  379. env.AddToVSProject(env.editor_sources)
  380. # windows allows us to have spaces in paths, so we need
  381. # to double quote off the directory. However, the path ends
  382. # in a backslash, so we need to remove this, lest it escape the
  383. # last double quote off, confusing MSBuild
  384. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  385. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  386. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  387. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  388. # required for Visual Studio to understand that it needs to generate an NMAKE
  389. # project. Do not modify without knowing what you are doing.
  390. debug_variants = ['debug|Win32'] + ['debug|x64']
  391. release_variants = ['release|Win32'] + ['release|x64']
  392. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  393. variants = debug_variants + release_variants + release_debug_variants
  394. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  395. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  396. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  397. targets = debug_targets + release_targets + release_debug_targets
  398. if not env.get('MSVS'):
  399. env['MSVS']['PROJECTSUFFIX'] = '.vcxproj'
  400. env['MSVS']['SOLUTIONSUFFIX'] = '.sln'
  401. env.MSVSProject(
  402. target=['#godot' + env['MSVSPROJECTSUFFIX']],
  403. incs=env.vs_incs,
  404. srcs=env.vs_srcs,
  405. runfile=targets,
  406. buildtarget=targets,
  407. auto_build_solution=1,
  408. variant=variants)
  409. else:
  410. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  411. def precious_program(env, program, sources, **args):
  412. program = env.ProgramOriginal(program, sources, **args)
  413. env.Precious(program)
  414. return program
  415. def add_shared_library(env, name, sources, **args):
  416. library = env.SharedLibrary(name, sources, **args)
  417. env.NoCache(library)
  418. return library
  419. def add_library(env, name, sources, **args):
  420. library = env.Library(name, sources, **args)
  421. env.NoCache(library)
  422. return library
  423. def add_program(env, name, sources, **args):
  424. program = env.Program(name, sources, **args)
  425. env.NoCache(program)
  426. return program
  427. def CommandNoCache(env, target, sources, command, **args):
  428. result = env.Command(target, sources, command, **args)
  429. env.NoCache(result)
  430. return result
  431. def detect_darwin_sdk_path(platform, env):
  432. sdk_name = ''
  433. if platform == 'osx':
  434. sdk_name = 'macosx'
  435. var_name = 'MACOS_SDK_PATH'
  436. elif platform == 'iphone':
  437. sdk_name = 'iphoneos'
  438. var_name = 'IPHONESDK'
  439. elif platform == 'iphonesimulator':
  440. sdk_name = 'iphonesimulator'
  441. var_name = 'IPHONESDK'
  442. else:
  443. raise Exception("Invalid platform argument passed to detect_darwin_sdk_path")
  444. if not env[var_name]:
  445. try:
  446. sdk_path = decode_utf8(subprocess.check_output(['xcrun', '--sdk', sdk_name, '--show-sdk-path']).strip())
  447. if sdk_path:
  448. env[var_name] = sdk_path
  449. except (subprocess.CalledProcessError, OSError):
  450. print("Failed to find SDK path while running xcrun --sdk {} --show-sdk-path.".format(sdk_name))
  451. raise
  452. def is_vanilla_clang(env):
  453. if not using_clang(env):
  454. return False
  455. version = decode_utf8(subprocess.check_output([env['CXX'], '--version']).strip())
  456. return not version.startswith("Apple")
  457. def get_compiler_version(env):
  458. if using_gcc(env):
  459. version = decode_utf8(subprocess.check_output([env['CXX'], '-dumpversion']).strip())
  460. elif using_clang(env):
  461. # Not using -dumpversion as it used to return 4.2.1: https://reviews.llvm.org/D56803
  462. version = decode_utf8(subprocess.check_output([env['CXX'], '--version']).strip())
  463. else: # TODO: Implement for MSVC
  464. return None
  465. match = re.search('[0-9][0-9.]*', version)
  466. if match is not None:
  467. return match.group().split('.')
  468. else:
  469. return None
  470. def using_gcc(env):
  471. return 'gcc' in os.path.basename(env["CC"])
  472. def using_clang(env):
  473. return 'clang' in os.path.basename(env["CC"])