methods.py 23 KB

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