Update pre-commit hooks configuration to use `ruff` instead of `black`

This commit is contained in:
Jakub Marcowski 2024-05-21 15:14:59 +02:00 committed by Thaddeus Crews
parent aaa4560729
commit d9f8ef68df
No known key found for this signature in database
GPG Key ID: 62181B86FE9E5D84
47 changed files with 244 additions and 241 deletions

View File

@ -17,12 +17,12 @@ repos:
platform/android/java/lib/src/com/.* platform/android/java/lib/src/com/.*
) )
- repo: https://github.com/psf/black-pre-commit-mirror - repo: https://github.com/astral-sh/ruff-pre-commit
rev: 24.2.0 rev: v0.4.4
hooks: hooks:
- id: black - id: ruff
files: (\.py$|SConstruct|SCsub) args: [--fix]
types_or: [text] - id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.971 rev: v0.971

View File

@ -10,11 +10,11 @@ import os
import pickle import pickle
import sys import sys
import time import time
from types import ModuleType
from collections import OrderedDict from collections import OrderedDict
from importlib.util import spec_from_file_location, module_from_spec from importlib.util import module_from_spec, spec_from_file_location
from SCons import __version__ as scons_raw_version from types import ModuleType
from SCons import __version__ as scons_raw_version
# Explicitly resolve the helper modules, this is done to avoid clash with # Explicitly resolve the helper modules, this is done to avoid clash with
# modules of the same name that might be randomly added (e.g. someone adding # modules of the same name that might be randomly added (e.g. someone adding
@ -53,12 +53,12 @@ _helper_module("core.core_builders", "core/core_builders.py")
_helper_module("main.main_builders", "main/main_builders.py") _helper_module("main.main_builders", "main/main_builders.py")
# Local # Local
import methods
import glsl_builders
import gles3_builders import gles3_builders
import glsl_builders
import methods
import scu_builders import scu_builders
from methods import print_warning, print_error from methods import print_error, print_warning
from platform_methods import architectures, architecture_aliases from platform_methods import architecture_aliases, architectures
if ARGUMENTS.get("target", "editor") == "editor": if ARGUMENTS.get("target", "editor") == "editor":
_helper_module("editor.editor_builders", "editor/editor_builders.py") _helper_module("editor.editor_builders", "editor/editor_builders.py")
@ -68,7 +68,7 @@ if ARGUMENTS.get("target", "editor") == "editor":
# <https://github.com/python/cpython/issues/73245> # <https://github.com/python/cpython/issues/73245>
if sys.stdout.isatty() and sys.platform == "win32": if sys.stdout.isatty() and sys.platform == "win32":
try: try:
from ctypes import windll, byref, WinError # type: ignore from ctypes import WinError, byref, windll # type: ignore
from ctypes.wintypes import DWORD # type: ignore from ctypes.wintypes import DWORD # type: ignore
stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11)) stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11))
@ -562,7 +562,7 @@ if env["build_profile"] != "":
dbo = ft["disabled_build_options"] dbo = ft["disabled_build_options"]
for c in dbo: for c in dbo:
env[c] = dbo[c] env[c] = dbo[c]
except: except json.JSONDecodeError:
print_error('Failed to open feature build profile: "{}"'.format(env["build_profile"])) print_error('Failed to open feature build profile: "{}"'.format(env["build_profile"]))
Exit(255) Exit(255)
@ -570,7 +570,7 @@ if env["build_profile"] != "":
# These can sometimes override default options. # These can sometimes override default options.
flag_list = platform_flags[env["platform"]] flag_list = platform_flags[env["platform"]]
for f in flag_list: for f in flag_list:
if not (f[0] in ARGUMENTS) or ARGUMENTS[f[0]] == "auto": # Allow command line to override platform flags if f[0] not in ARGUMENTS or ARGUMENTS[f[0]] == "auto": # Allow command line to override platform flags
env[f[0]] = f[1] env[f[0]] = f[1]
# 'dev_mode' and 'production' are aliases to set default options if they haven't been # 'dev_mode' and 'production' are aliases to set default options if they haven't been
@ -591,7 +591,7 @@ if env["production"]:
# Run SCU file generation script if in a SCU build. # Run SCU file generation script if in a SCU build.
if env["scu_build"]: if env["scu_build"]:
max_includes_per_scu = 8 max_includes_per_scu = 8
if env.dev_build == True: if env.dev_build:
max_includes_per_scu = 1024 max_includes_per_scu = 1024
read_scu_limit = int(env["scu_limit"]) read_scu_limit = int(env["scu_limit"])
@ -984,7 +984,7 @@ GLSL_BUILDERS = {
env.Append(BUILDERS=GLSL_BUILDERS) env.Append(BUILDERS=GLSL_BUILDERS)
scons_cache_path = os.environ.get("SCONS_CACHE") scons_cache_path = os.environ.get("SCONS_CACHE")
if scons_cache_path != None: if scons_cache_path is not None:
CacheDir(scons_cache_path) CacheDir(scons_cache_path)
print("Scons cache enabled... (path: '" + scons_cache_path + "')") print("Scons cache enabled... (path: '" + scons_cache_path + "')")

View File

@ -2,10 +2,12 @@
Import("env") Import("env")
import core_builders
import methods
import os import os
import core_builders
import methods
env.core_sources = [] env.core_sources = []
# Add required thirdparty code. # Add required thirdparty code.
@ -188,9 +190,7 @@ def version_info_builder(target, source, env):
#define VERSION_WEBSITE "{website}" #define VERSION_WEBSITE "{website}"
#define VERSION_DOCS_BRANCH "{docs_branch}" #define VERSION_DOCS_BRANCH "{docs_branch}"
#define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH #define VERSION_DOCS_URL "https://docs.godotengine.org/en/" VERSION_DOCS_BRANCH
""".format( """.format(**env.version_info)
**env.version_info
)
) )
@ -206,9 +206,7 @@ def version_hash_builder(target, source, env):
const char *const VERSION_HASH = "{git_hash}"; const char *const VERSION_HASH = "{git_hash}";
const uint64_t VERSION_TIMESTAMP = {git_timestamp}; const uint64_t VERSION_TIMESTAMP = {git_timestamp};
""".format( """.format(**env.version_info)
**env.version_info
)
) )

View File

@ -180,7 +180,7 @@ def make_license_header(target, source, env):
return line return line
def next_tag(self): def next_tag(self):
if not ":" in self.current: if ":" not in self.current:
return ("", []) return ("", [])
tag, line = self.current.split(":", 1) tag, line = self.current.split(":", 1)
lines = [line.strip()] lines = [line.strip()]
@ -206,7 +206,7 @@ def make_license_header(target, source, env):
if not tag or not reader.current: if not tag or not reader.current:
# end of a paragraph start a new part # end of a paragraph start a new part
if "License" in part and not "Files" in part: if "License" in part and "Files" not in part:
# no Files tag in this one, so assume standalone license # no Files tag in this one, so assume standalone license
license_list.append(part["License"]) license_list.append(part["License"])
part = {} part = {}
@ -298,13 +298,13 @@ def make_license_header(target, source, env):
f.write("const int LICENSE_COUNT = " + str(len(license_list)) + ";\n") f.write("const int LICENSE_COUNT = " + str(len(license_list)) + ";\n")
f.write("const char *const LICENSE_NAMES[] = {\n") f.write("const char *const LICENSE_NAMES[] = {\n")
for l in license_list: for license in license_list:
f.write('\t"' + escape_string(l[0]) + '",\n') f.write('\t"' + escape_string(license[0]) + '",\n')
f.write("};\n\n") f.write("};\n\n")
f.write("const char *const LICENSE_BODIES[] = {\n\n") f.write("const char *const LICENSE_BODIES[] = {\n\n")
for l in license_list: for license in license_list:
for line in l[1:]: for line in license[1:]:
if line == ".": if line == ".":
f.write('\t"\\n"\n') f.write('\t"\\n"\n')
else: else:

View File

@ -2,8 +2,8 @@
Import("env") Import("env")
import make_wrappers
import make_interface_dumper import make_interface_dumper
import make_wrappers
env.CommandNoCache(["ext_wrappers.gen.inc"], "make_wrappers.py", env.Run(make_wrappers.run)) env.CommandNoCache(["ext_wrappers.gen.inc"], "make_wrappers.py", env.Run(make_wrappers.run))
env.CommandNoCache( env.CommandNoCache(

View File

@ -10,7 +10,6 @@ _FORCE_INLINE_ virtual $RETVAL m_name($FUNCARGS) $CONST override { \\
def generate_mod_version(argcount, const=False, returns=False): def generate_mod_version(argcount, const=False, returns=False):
s = proto_mod s = proto_mod
sproto = str(argcount) sproto = str(argcount)
method_info = ""
if returns: if returns:
sproto += "R" sproto += "R"
s = s.replace("$RETTYPE", "m_ret, ") s = s.replace("$RETTYPE", "m_ret, ")
@ -68,7 +67,6 @@ virtual $RETVAL m_name($FUNCARGS) $CONST override { \\
def generate_ex_version(argcount, const=False, returns=False): def generate_ex_version(argcount, const=False, returns=False):
s = proto_ex s = proto_ex
sproto = str(argcount) sproto = str(argcount)
method_info = ""
if returns: if returns:
sproto += "R" sproto += "R"
s = s.replace("$RETTYPE", "m_ret, ") s = s.replace("$RETTYPE", "m_ret, ")

View File

@ -4,7 +4,6 @@ Import("env")
import input_builders import input_builders
# Order matters here. Higher index controller database files write on top of lower index database files. # Order matters here. Higher index controller database files write on top of lower index database files.
controller_databases = [ controller_databases = [
"gamecontrollerdb.txt", "gamecontrollerdb.txt",

View File

@ -1,11 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import fnmatch import fnmatch
import os
import sys
import re
import math import math
import os
import platform import platform
import re
import sys
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from typing import Dict, List, Set from typing import Dict, List, Set
@ -286,7 +286,7 @@ class ClassStatus:
status.progresses[tag.tag].increment(is_deprecated or is_experimental or has_descr) status.progresses[tag.tag].increment(is_deprecated or is_experimental or has_descr)
elif tag.tag in ["constants", "members", "theme_items"]: elif tag.tag in ["constants", "members", "theme_items"]:
for sub_tag in list(tag): for sub_tag in list(tag):
if not sub_tag.text is None: if sub_tag.text is not None:
is_deprecated = "deprecated" in sub_tag.attrib is_deprecated = "deprecated" in sub_tag.attrib
is_experimental = "experimental" in sub_tag.attrib is_experimental = "experimental" in sub_tag.attrib
has_descr = len(sub_tag.text.strip()) > 0 has_descr = len(sub_tag.text.strip()) > 0

View File

@ -4,17 +4,16 @@
import argparse import argparse
import os import os
import platform
import re import re
import sys import sys
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from collections import OrderedDict from collections import OrderedDict
from typing import List, Dict, TextIO, Tuple, Optional, Any, Union from typing import Any, Dict, List, Optional, TextIO, Tuple, Union
# Import hardcoded version information from version.py # Import hardcoded version information from version.py
root_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../") root_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../")
sys.path.append(root_directory) # Include the root directory sys.path.append(root_directory) # Include the root directory
import version import version # noqa: E402
# $DOCS_URL/path/to/page.html(#fragment-tag) # $DOCS_URL/path/to/page.html(#fragment-tag)
GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$") GODOT_DOCS_PATTERN = re.compile(r"^\$DOCS_URL/(.*)\.html(#.*)?$")
@ -706,7 +705,7 @@ def main() -> None:
# <https://github.com/python/cpython/issues/73245> # <https://github.com/python/cpython/issues/73245>
if should_color and sys.stdout.isatty() and sys.platform == "win32": if should_color and sys.stdout.isatty() and sys.platform == "win32":
try: try:
from ctypes import windll, byref, WinError # type: ignore from ctypes import WinError, byref, windll # type: ignore
from ctypes.wintypes import DWORD # type: ignore from ctypes.wintypes import DWORD # type: ignore
stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11)) stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11))
@ -1413,7 +1412,7 @@ def make_rst_class(class_def: ClassDef, state: State, dry_run: bool, output_dir:
operator_anchor = f".. _class_{class_name}_operator_{sanitize_operator_name(m.name, state)}" operator_anchor = f".. _class_{class_name}_operator_{sanitize_operator_name(m.name, state)}"
for parameter in m.parameters: for parameter in m.parameters:
operator_anchor += f"_{parameter.type_name.type_name}" operator_anchor += f"_{parameter.type_name.type_name}"
operator_anchor += f":\n\n" operator_anchor += ":\n\n"
f.write(operator_anchor) f.write(operator_anchor)
f.write(".. rst-class:: classref-operator\n\n") f.write(".. rst-class:: classref-operator\n\n")
@ -1553,7 +1552,7 @@ def make_method_signature(
out += f":ref:`{op_name}<class_{class_def.name}_{ref_type}_{sanitize_operator_name(definition.name, state)}" out += f":ref:`{op_name}<class_{class_def.name}_{ref_type}_{sanitize_operator_name(definition.name, state)}"
for parameter in definition.parameters: for parameter in definition.parameters:
out += f"_{parameter.type_name.type_name}" out += f"_{parameter.type_name.type_name}"
out += f">`" out += ">`"
elif ref_type == "method": elif ref_type == "method":
ref_type_qualifier = "" ref_type_qualifier = ""
if definition.name.startswith("_"): if definition.name.startswith("_"):

View File

@ -4,11 +4,12 @@ Import("env")
env.editor_sources = [] env.editor_sources = []
import os
import glob import glob
import editor_builders import os
import methods
import editor_builders
import methods
if env.editor_build: if env.editor_build:
# Generate doc data paths # Generate doc data paths

View File

@ -7,6 +7,7 @@ import subprocess
import tempfile import tempfile
import uuid import uuid
import zlib import zlib
from methods import print_warning from methods import print_warning

View File

@ -3,8 +3,8 @@
Import("env") Import("env")
import os import os
import editor_icons_builders
import editor_icons_builders
env["BUILDERS"]["MakeEditorIconsBuilder"] = Builder( env["BUILDERS"]["MakeEditorIconsBuilder"] = Builder(
action=env.Run(editor_icons_builders.make_editor_icons_action), action=env.Run(editor_icons_builders.make_editor_icons_action),

View File

@ -3,8 +3,8 @@
Import("env") Import("env")
import glob import glob
import editor_theme_builders
import editor_theme_builders
# Fonts # Fonts
flist = glob.glob(env.Dir("#thirdparty").abspath + "/fonts/*.ttf") flist = glob.glob(env.Dir("#thirdparty").abspath + "/fonts/*.ttf")

View File

@ -1,9 +1,10 @@
"""Functions used to generate source files during build time""" """Functions used to generate source files during build time"""
import os.path import os.path
from methods import print_error
from typing import Optional from typing import Optional
from methods import print_error
class GLES3HeaderStruct: class GLES3HeaderStruct:
def __init__(self): def __init__(self):
@ -91,11 +92,11 @@ def include_file_in_gles3_header(filename: str, header_data: GLES3HeaderStruct,
includeline = line.replace("#include ", "").strip()[1:-1] includeline = line.replace("#include ", "").strip()[1:-1]
included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline) included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline)
if not included_file in header_data.vertex_included_files and header_data.reading == "vertex": if included_file not in header_data.vertex_included_files and header_data.reading == "vertex":
header_data.vertex_included_files += [included_file] header_data.vertex_included_files += [included_file]
if include_file_in_gles3_header(included_file, header_data, depth + 1) is None: if include_file_in_gles3_header(included_file, header_data, depth + 1) is None:
print_error(f'In file "{filename}": #include "{includeline}" could not be found!"') print_error(f'In file "{filename}": #include "{includeline}" could not be found!"')
elif not included_file in header_data.fragment_included_files and header_data.reading == "fragment": elif included_file not in header_data.fragment_included_files and header_data.reading == "fragment":
header_data.fragment_included_files += [included_file] header_data.fragment_included_files += [included_file]
if include_file_in_gles3_header(included_file, header_data, depth + 1) is None: if include_file_in_gles3_header(included_file, header_data, depth + 1) is None:
print_error(f'In file "{filename}": #include "{includeline}" could not be found!"') print_error(f'In file "{filename}": #include "{includeline}" could not be found!"')
@ -121,7 +122,7 @@ def include_file_in_gles3_header(filename: str, header_data: GLES3HeaderStruct,
# unfiorm array # unfiorm array
x = x[: x.find("[")] x = x[: x.find("[")]
if not x in header_data.texunit_names: if x not in header_data.texunit_names:
header_data.texunits += [(x, texunit)] header_data.texunits += [(x, texunit)]
header_data.texunit_names += [x] header_data.texunit_names += [x]
@ -142,7 +143,7 @@ def include_file_in_gles3_header(filename: str, header_data: GLES3HeaderStruct,
# unfiorm array # unfiorm array
x = x[: x.find("[")] x = x[: x.find("[")]
if not x in header_data.ubo_names: if x not in header_data.ubo_names:
header_data.ubos += [(x, ubo)] header_data.ubos += [(x, ubo)]
header_data.ubo_names += [x] header_data.ubo_names += [x]
@ -157,7 +158,7 @@ def include_file_in_gles3_header(filename: str, header_data: GLES3HeaderStruct,
# unfiorm array # unfiorm array
x = x[: x.find("[")] x = x[: x.find("[")]
if not x in header_data.uniforms: if x not in header_data.uniforms:
header_data.uniforms += [x] header_data.uniforms += [x]
if (line.strip().find("out ") == 0 or line.strip().find("flat ") == 0) and line.find("tfb:") != -1: if (line.strip().find("out ") == 0 or line.strip().find("flat ") == 0) and line.find("tfb:") != -1:

View File

@ -1,8 +1,9 @@
"""Functions used to generate source files during build time""" """Functions used to generate source files during build time"""
import os.path import os.path
from typing import Iterable, Optional
from methods import print_error from methods import print_error
from typing import Optional, Iterable
def generate_inline_code(input_lines: Iterable[str], insert_newline: bool = True): def generate_inline_code(input_lines: Iterable[str], insert_newline: bool = True):
@ -77,15 +78,15 @@ def include_file_in_rd_header(filename: str, header_data: RDHeaderStruct, depth:
else: else:
included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline) included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline)
if not included_file in header_data.vertex_included_files and header_data.reading == "vertex": if included_file not in header_data.vertex_included_files and header_data.reading == "vertex":
header_data.vertex_included_files += [included_file] header_data.vertex_included_files += [included_file]
if include_file_in_rd_header(included_file, header_data, depth + 1) is None: if include_file_in_rd_header(included_file, header_data, depth + 1) is None:
print_error(f'In file "{filename}": #include "{includeline}" could not be found!"') print_error(f'In file "{filename}": #include "{includeline}" could not be found!"')
elif not included_file in header_data.fragment_included_files and header_data.reading == "fragment": elif included_file not in header_data.fragment_included_files and header_data.reading == "fragment":
header_data.fragment_included_files += [included_file] header_data.fragment_included_files += [included_file]
if include_file_in_rd_header(included_file, header_data, depth + 1) is None: if include_file_in_rd_header(included_file, header_data, depth + 1) is None:
print_error(f'In file "{filename}": #include "{includeline}" could not be found!"') print_error(f'In file "{filename}": #include "{includeline}" could not be found!"')
elif not included_file in header_data.compute_included_files and header_data.reading == "compute": elif included_file not in header_data.compute_included_files and header_data.reading == "compute":
header_data.compute_included_files += [included_file] header_data.compute_included_files += [included_file]
if include_file_in_rd_header(included_file, header_data, depth + 1) is None: if include_file_in_rd_header(included_file, header_data, depth + 1) is None:
print_error(f'In file "{filename}": #include "{includeline}" could not be found!"') print_error(f'In file "{filename}": #include "{includeline}" could not be found!"')

View File

@ -1,17 +1,14 @@
import os
import sys
import re
import glob
import subprocess
import contextlib import contextlib
import glob
import os
import re
import subprocess
import sys
from collections import OrderedDict from collections import OrderedDict
from collections.abc import Mapping
from enum import Enum from enum import Enum
from typing import Generator, Optional from io import StringIO, TextIOWrapper
from io import TextIOWrapper, StringIO
from pathlib import Path from pathlib import Path
from os.path import normpath, basename from typing import Generator, Optional
# Get the "Godot" folder name ahead of time # Get the "Godot" folder name ahead of time
base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/" base_folder_path = str(os.path.abspath(Path(__file__).parent)) + "/"
@ -199,7 +196,7 @@ def add_module_version_string(self, s):
def get_version_info(module_version_string="", silent=False): def get_version_info(module_version_string="", silent=False):
build_name = "custom_build" build_name = "custom_build"
if os.getenv("BUILD_NAME") != None: if os.getenv("BUILD_NAME") is not None:
build_name = str(os.getenv("BUILD_NAME")) build_name = str(os.getenv("BUILD_NAME"))
if not silent: if not silent:
print(f"Using custom build name: '{build_name}'.") print(f"Using custom build name: '{build_name}'.")
@ -221,7 +218,7 @@ def get_version_info(module_version_string="", silent=False):
# For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git, # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git,
# so this define provides a way to override it without having to modify the source. # so this define provides a way to override it without having to modify the source.
if os.getenv("GODOT_VERSION_STATUS") != None: if os.getenv("GODOT_VERSION_STATUS") is not None:
version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS")) version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS"))
if not silent: if not silent:
print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.") print(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.")
@ -435,7 +432,7 @@ def module_check_dependencies(self, module):
required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else [] required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
for dep in required_deps: for dep in required_deps:
opt = "module_{}_enabled".format(dep) opt = "module_{}_enabled".format(dep)
if not opt in self or not self[opt]: if opt not in self or not self[opt]:
missing_deps.append(dep) missing_deps.append(dep)
if missing_deps != []: if missing_deps != []:
@ -450,7 +447,6 @@ def module_check_dependencies(self, module):
def sort_module_list(env): def sort_module_list(env):
out = OrderedDict()
deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()} deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()}
frontier = list(env.module_list.keys()) frontier = list(env.module_list.keys())
@ -650,7 +646,7 @@ def detect_visual_c_compiler_version(tools_env):
def find_visual_c_batch_file(env): def find_visual_c_batch_file(env):
from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file, find_vc_pdir from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target
msvc_version = get_default_version(env) msvc_version = get_default_version(env)
@ -696,10 +692,7 @@ def glob_recursive(pattern, node="."):
def add_to_vs_project(env, sources): def add_to_vs_project(env, sources):
for x in sources: for x in sources:
if type(x) == type(""): fname = env.File(x).path if isinstance(x, str) else env.File(x)[0].path
fname = env.File(x).path
else:
fname = env.File(x)[0].path
pieces = fname.split(".") pieces = fname.split(".")
if len(pieces) > 0: if len(pieces) > 0:
basename = pieces[0] basename = pieces[0]
@ -884,7 +877,8 @@ def show_progress(env):
return return
import sys import sys
from SCons.Script import Progress, Command, AlwaysBuild
from SCons.Script import AlwaysBuild, Command, Progress
screen = sys.stdout screen = sys.stdout
# Progress reporting is not available in non-TTY environments since it # Progress reporting is not available in non-TTY environments since it
@ -895,7 +889,8 @@ def show_progress(env):
node_count_interval = 1 node_count_interval = 1
node_count_fname = str(env.Dir("#")) + "/.scons_node_count" node_count_fname = str(env.Dir("#")) + "/.scons_node_count"
import time, math import math
import time
class cache_progress: class cache_progress:
# The default is 1 GB cache and 12 hours half life # The default is 1 GB cache and 12 hours half life
@ -903,7 +898,7 @@ def show_progress(env):
self.path = path self.path = path
self.limit = limit self.limit = limit
self.exponent_scale = math.log(2) / half_life self.exponent_scale = math.log(2) / half_life
if env["verbose"] and path != None: if env["verbose"] and path is not None:
screen.write( screen.write(
"Current cache limit is {} (used: {})\n".format( "Current cache limit is {} (used: {})\n".format(
self.convert_size(limit), self.convert_size(self.get_size(path)) self.convert_size(limit), self.convert_size(self.get_size(path))
@ -1049,11 +1044,11 @@ def generate_vs_project(env, original_args, project_name="godot"):
if type(f) is Node.FS.Dir: if type(f) is Node.FS.Dir:
results += glob_recursive_2(pattern, dirs, f) results += glob_recursive_2(pattern, dirs, f)
r = Glob(str(node) + "/" + pattern, source=True) r = Glob(str(node) + "/" + pattern, source=True)
if len(r) > 0 and not str(node) in dirs: if len(r) > 0 and str(node) not in dirs:
d = "" d = ""
for part in str(node).split("\\"): for part in str(node).split("\\"):
d += part d += part
if not d in dirs: if d not in dirs:
dirs.append(d) dirs.append(d)
d += "\\" d += "\\"
results += r results += r
@ -1066,7 +1061,7 @@ def generate_vs_project(env, original_args, project_name="godot"):
if val is not None: if val is not None:
try: try:
return _text2bool(val) return _text2bool(val)
except: except (ValueError, AttributeError):
return default return default
else: else:
return default return default
@ -1239,13 +1234,13 @@ def generate_vs_project(env, original_args, project_name="godot"):
others_active = [] others_active = []
for x in envsources: for x in envsources:
fname = "" fname = ""
if type(x) == type(""): if isinstance(x, str):
fname = env.File(x).path fname = env.File(x).path
else: else:
# Some object files might get added directly as a File object and not a list. # Some object files might get added directly as a File object and not a list.
try: try:
fname = env.File(x)[0].path fname = env.File(x)[0].path
except: except Exception:
fname = x.path fname = x.path
pass pass
@ -1324,7 +1319,7 @@ def generate_vs_project(env, original_args, project_name="godot"):
itemlist = {} itemlist = {}
for item in activeItems: for item in activeItems:
key = os.path.dirname(item).replace("\\", "_") key = os.path.dirname(item).replace("\\", "_")
if not key in itemlist: if key not in itemlist:
itemlist[key] = [item] itemlist[key] = [item]
else: else:
itemlist[key] += [item] itemlist[key] += [item]
@ -1465,14 +1460,14 @@ def generate_vs_project(env, original_args, project_name="godot"):
if godot_platform != "windows": if godot_platform != "windows":
configurations += [ configurations += [
f'<ProjectConfiguration Include="editor|{proj_plat}">', f'<ProjectConfiguration Include="editor|{proj_plat}">',
f" <Configuration>editor</Configuration>", " <Configuration>editor</Configuration>",
f" <Platform>{proj_plat}</Platform>", f" <Platform>{proj_plat}</Platform>",
"</ProjectConfiguration>", "</ProjectConfiguration>",
] ]
properties += [ properties += [
f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">", f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">",
f" <GodotConfiguration>editor</GodotConfiguration>", " <GodotConfiguration>editor</GodotConfiguration>",
f" <GodotPlatform>{proj_plat}</GodotPlatform>", f" <GodotPlatform>{proj_plat}</GodotPlatform>",
"</PropertyGroup>", "</PropertyGroup>",
] ]

View File

@ -1,15 +1,15 @@
#!/usr/bin/env python #!/usr/bin/env python
import os import os
import urllib.request
import shutil import shutil
import subprocess import subprocess
import sys import sys
import urllib.request
# Enable ANSI escape code support on Windows 10 and later (for colored console output). # Enable ANSI escape code support on Windows 10 and later (for colored console output).
# <https://github.com/python/cpython/issues/73245> # <https://github.com/python/cpython/issues/73245>
if sys.platform == "win32": if sys.platform == "win32":
from ctypes import windll, c_int, byref from ctypes import byref, c_int, windll
stdout_handle = windll.kernel32.GetStdHandle(c_int(-11)) stdout_handle = windll.kernel32.GetStdHandle(c_int(-11))
mode = c_int(0) mode = c_int(0)

View File

@ -1,8 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
import methods
import os import os
import methods
Import("env") Import("env")
env_modules = env.Clone() env_modules = env.Clone()

View File

@ -5,7 +5,7 @@ import os.path
import shlex import shlex
import subprocess import subprocess
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional, List from typing import List, Optional
def find_dotnet_cli(): def find_dotnet_cli():
@ -304,9 +304,7 @@ def generate_sdk_package_versions():
<GodotVersionConstants>{1}</GodotVersionConstants> <GodotVersionConstants>{1}</GodotVersionConstants>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
""".format( """.format(version_str, ";".join(version_defines))
version_str, ";".join(version_defines)
)
# We write in ../SdkPackageVersions.props. # We write in ../SdkPackageVersions.props.
with open(os.path.join(dirname(script_path), "SdkPackageVersions.props"), "w", encoding="utf-8", newline="\n") as f: with open(os.path.join(dirname(script_path), "SdkPackageVersions.props"), "w", encoding="utf-8", newline="\n") as f:
@ -323,9 +321,7 @@ def generate_sdk_package_versions():
public const string VersionDocsUrl = "https://docs.godotengine.org/en/{docs_branch}"; public const string VersionDocsUrl = "https://docs.godotengine.org/en/{docs_branch}";
}} }}
}} }}
""".format( """.format(**version_info)
**version_info
)
generators_dir = os.path.join( generators_dir = os.path.join(
dirname(script_path), dirname(script_path),

View File

@ -1,7 +1,3 @@
import os
import os.path
def is_desktop(platform): def is_desktop(platform):
return platform in ["windows", "macos", "linuxbsd"] return platform in ["windows", "macos", "linuxbsd"]

View File

@ -12,7 +12,7 @@ def configure(env):
# Check if the platform has marked mono as supported. # Check if the platform has marked mono as supported.
supported = env.get("supported", []) supported = env.get("supported", [])
if not "mono" in supported: if "mono" not in supported:
raise RuntimeError("This module does not currently support building for this platform") raise RuntimeError("This module does not currently support building for this platform")
env.add_module_version_string("mono") env.add_module_version_string("mono")

View File

@ -1,14 +1,15 @@
#!/usr/bin/env python #!/usr/bin/env python
import atexit import atexit
import sys import sys
import methods
import time import time
import methods
# Enable ANSI escape code support on Windows 10 and later (for colored console output). # Enable ANSI escape code support on Windows 10 and later (for colored console output).
# <https://github.com/python/cpython/issues/73245> # <https://github.com/python/cpython/issues/73245>
if sys.stdout.isatty() and sys.platform == "win32": if sys.stdout.isatty() and sys.platform == "win32":
try: try:
from ctypes import windll, byref, WinError # type: ignore from ctypes import WinError, byref, windll # type: ignore
from ctypes.wintypes import DWORD # type: ignore from ctypes.wintypes import DWORD # type: ignore
stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11)) stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11))
@ -720,7 +721,7 @@ if env["static_icu_data"]:
env.Append(CXXFLAGS=["-DICU_STATIC_DATA"]) env.Append(CXXFLAGS=["-DICU_STATIC_DATA"])
env.Append(CPPPATH=["../../../thirdparty/icu4c/"]) env.Append(CPPPATH=["../../../thirdparty/icu4c/"])
else: else:
thirdparty_sources += ["../icu_data/icudata_stub.cpp"] thirdparty_icu_sources += ["../icu_data/icudata_stub.cpp"]
env_icu.Append(CPPPATH=["../../../thirdparty/icu4c/common/", "../../../thirdparty/icu4c/i18n/"]) env_icu.Append(CPPPATH=["../../../thirdparty/icu4c/common/", "../../../thirdparty/icu4c/i18n/"])
env_icu.Append( env_icu.Append(

View File

@ -81,9 +81,9 @@ def disable_warnings(self):
self.Append(CCFLAGS=["/w"]) self.Append(CCFLAGS=["/w"])
self.Append(CFLAGS=["/w"]) self.Append(CFLAGS=["/w"])
self.Append(CXXFLAGS=["/w"]) self.Append(CXXFLAGS=["/w"])
self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x in warn_flags] self["CCFLAGS"] = [x for x in self["CCFLAGS"] if x not in warn_flags]
self["CFLAGS"] = [x for x in self["CFLAGS"] if not x in warn_flags] self["CFLAGS"] = [x for x in self["CFLAGS"] if x not in warn_flags]
self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x in warn_flags] self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if x not in warn_flags]
else: else:
self.Append(CCFLAGS=["-w"]) self.Append(CCFLAGS=["-w"])
self.Append(CFLAGS=["-w"]) self.Append(CFLAGS=["-w"])
@ -117,31 +117,31 @@ def make_icu_data(target, source, env):
def write_macos_plist(target, binary_name, identifier, name): def write_macos_plist(target, binary_name, identifier, name):
os.makedirs(f"{target}/Resource/", exist_ok=True) os.makedirs(f"{target}/Resource/", exist_ok=True)
with open(f"{target}/Resource/Info.plist", "w", encoding="utf-8", newline="\n") as f: with open(f"{target}/Resource/Info.plist", "w", encoding="utf-8", newline="\n") as f:
f.write(f'<?xml version="1.0" encoding="UTF-8"?>\n') f.write(f"""\
f.write( <?xml version="1.0" encoding="UTF-8"?>
f'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n' <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
) <plist version="1.0">
f.write(f'<plist version="1.0">\n') <dict>
f.write(f"<dict>\n") <key>CFBundleExecutable</key>
f.write(f"\t<key>CFBundleExecutable</key>\n") <string>{binary_name}</string>
f.write(f"\t<string>{binary_name}</string>\n") <key>CFBundleIdentifier</key>
f.write(f"\t<key>CFBundleIdentifier</key>\n") <string>{identifier}</string>
f.write(f"\t<string>{identifier}</string>\n") <key>CFBundleInfoDictionaryVersion</key>
f.write(f"\t<key>CFBundleInfoDictionaryVersion</key>\n") <string>6.0</string>
f.write(f"\t<string>6.0</string>\n") <key>CFBundleName</key>
f.write(f"\t<key>CFBundleName</key>\n") <string>{name}</string>
f.write(f"\t<string>{name}</string>\n") <key>CFBundlePackageType</key>
f.write(f"\t<key>CFBundlePackageType</key>\n") <string>FMWK</string>
f.write(f"\t<string>FMWK</string>\n") <key>CFBundleShortVersionString</key>
f.write(f"\t<key>CFBundleShortVersionString</key>\n") <string>1.0.0</string>
f.write(f"\t<string>1.0.0</string>\n") <key>CFBundleSupportedPlatforms</key>
f.write(f"\t<key>CFBundleSupportedPlatforms</key>\n") <array>
f.write(f"\t<array>\n") <string>MacOSX</string>
f.write(f"\t\t<string>MacOSX</string>\n") </array>
f.write(f"\t</array>\n") <key>CFBundleVersion</key>
f.write(f"\t<key>CFBundleVersion</key>\n") <string>1.0.0</string>
f.write(f"\t<string>1.0.0</string>\n") <key>LSMinimumSystemVersion</key>
f.write(f"\t<key>LSMinimumSystemVersion</key>\n") <string>10.14</string>
f.write(f"\t<string>10.14</string>\n") </dict>
f.write(f"</dict>\n") </plist>
f.write(f"</plist>\n") """)

View File

@ -1,14 +1,15 @@
#!/usr/bin/env python #!/usr/bin/env python
import atexit import atexit
import sys import sys
import methods
import time import time
import methods
# Enable ANSI escape code support on Windows 10 and later (for colored console output). # Enable ANSI escape code support on Windows 10 and later (for colored console output).
# <https://github.com/python/cpython/issues/73245> # <https://github.com/python/cpython/issues/73245>
if sys.stdout.isatty() and sys.platform == "win32": if sys.stdout.isatty() and sys.platform == "win32":
try: try:
from ctypes import windll, byref, WinError # type: ignore from ctypes import WinError, byref, windll # type: ignore
from ctypes.wintypes import DWORD # type: ignore from ctypes.wintypes import DWORD # type: ignore
stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11)) stdout_handle = windll.kernel32.GetStdHandle(DWORD(-11))

View File

@ -81,9 +81,9 @@ def disable_warnings(self):
self.Append(CCFLAGS=["/w"]) self.Append(CCFLAGS=["/w"])
self.Append(CFLAGS=["/w"]) self.Append(CFLAGS=["/w"])
self.Append(CXXFLAGS=["/w"]) self.Append(CXXFLAGS=["/w"])
self["CCFLAGS"] = [x for x in self["CCFLAGS"] if not x in warn_flags] self["CCFLAGS"] = [x for x in self["CCFLAGS"] if x not in warn_flags]
self["CFLAGS"] = [x for x in self["CFLAGS"] if not x in warn_flags] self["CFLAGS"] = [x for x in self["CFLAGS"] if x not in warn_flags]
self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if not x in warn_flags] self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if x not in warn_flags]
else: else:
self.Append(CCFLAGS=["-w"]) self.Append(CCFLAGS=["-w"])
self.Append(CFLAGS=["-w"]) self.Append(CFLAGS=["-w"])
@ -117,31 +117,31 @@ def make_icu_data(target, source, env):
def write_macos_plist(target, binary_name, identifier, name): def write_macos_plist(target, binary_name, identifier, name):
os.makedirs(f"{target}/Resource/", exist_ok=True) os.makedirs(f"{target}/Resource/", exist_ok=True)
with open(f"{target}/Resource/Info.plist", "w", encoding="utf-8", newline="\n") as f: with open(f"{target}/Resource/Info.plist", "w", encoding="utf-8", newline="\n") as f:
f.write(f'<?xml version="1.0" encoding="UTF-8"?>\n') f.write(f"""\
f.write( <?xml version="1.0" encoding="UTF-8"?>
f'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n' <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
) <plist version="1.0">
f.write(f'<plist version="1.0">\n') <dict>
f.write(f"<dict>\n") <key>CFBundleExecutable</key>
f.write(f"\t<key>CFBundleExecutable</key>\n") <string>{binary_name}</string>
f.write(f"\t<string>{binary_name}</string>\n") <key>CFBundleIdentifier</key>
f.write(f"\t<key>CFBundleIdentifier</key>\n") <string>{identifier}</string>
f.write(f"\t<string>{identifier}</string>\n") <key>CFBundleInfoDictionaryVersion</key>
f.write(f"\t<key>CFBundleInfoDictionaryVersion</key>\n") <string>6.0</string>
f.write(f"\t<string>6.0</string>\n") <key>CFBundleName</key>
f.write(f"\t<key>CFBundleName</key>\n") <string>{name}</string>
f.write(f"\t<string>{name}</string>\n") <key>CFBundlePackageType</key>
f.write(f"\t<key>CFBundlePackageType</key>\n") <string>FMWK</string>
f.write(f"\t<string>FMWK</string>\n") <key>CFBundleShortVersionString</key>
f.write(f"\t<key>CFBundleShortVersionString</key>\n") <string>1.0.0</string>
f.write(f"\t<string>1.0.0</string>\n") <key>CFBundleSupportedPlatforms</key>
f.write(f"\t<key>CFBundleSupportedPlatforms</key>\n") <array>
f.write(f"\t<array>\n") <string>MacOSX</string>
f.write(f"\t\t<string>MacOSX</string>\n") </array>
f.write(f"\t</array>\n") <key>CFBundleVersion</key>
f.write(f"\t<key>CFBundleVersion</key>\n") <string>1.0.0</string>
f.write(f"\t<string>1.0.0</string>\n") <key>LSMinimumSystemVersion</key>
f.write(f"\t<key>LSMinimumSystemVersion</key>\n") <string>10.14</string>
f.write(f"\t<string>10.14</string>\n") </dict>
f.write(f"</dict>\n") </plist>
f.write(f"</plist>\n") """)

View File

@ -1,9 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python
import methods
from glob import glob from glob import glob
from pathlib import Path from pathlib import Path
import methods
Import("env") Import("env")
env.platform_sources = [] env.platform_sources = []

View File

@ -1,7 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
import sys
import subprocess import subprocess
import sys
from methods import print_warning from methods import print_warning
Import("env") Import("env")

View File

@ -1,10 +1,11 @@
import os import os
import sys
import platform import platform
import subprocess import subprocess
from methods import print_warning, print_error import sys
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from methods import print_error, print_warning
if TYPE_CHECKING: if TYPE_CHECKING:
from SCons.Script.SConscript import SConsEnvironment from SCons.Script.SConscript import SConsEnvironment

View File

@ -2,11 +2,11 @@
Import("env") Import("env")
import os, json import os
from platform_methods import architectures, lipo, get_build_version, detect_mvk
import subprocess
import shutil import shutil
from platform_methods import detect_mvk, lipo
def generate_bundle(target, source, env): def generate_bundle(target, source, env):
bin_dir = Dir("#bin").abspath bin_dir = Dir("#bin").abspath

View File

@ -1,9 +1,9 @@
import os import os
import sys import sys
from methods import print_error, detect_darwin_sdk_path
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from methods import detect_darwin_sdk_path, print_error
if TYPE_CHECKING: if TYPE_CHECKING:
from SCons.Script.SConscript import SConsEnvironment from SCons.Script.SConscript import SConsEnvironment

View File

@ -1,11 +1,11 @@
import os import os
import platform import platform
import sys import sys
from methods import print_warning, print_error, get_compiler_version, using_gcc
from platform_methods import detect_arch
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from methods import get_compiler_version, print_error, print_warning, using_gcc
from platform_methods import detect_arch
if TYPE_CHECKING: if TYPE_CHECKING:
from SCons.Script.SConscript import SConsEnvironment from SCons.Script.SConscript import SConsEnvironment

View File

@ -2,11 +2,13 @@
Import("env") Import("env")
import os, json import os
from platform_methods import architectures, lipo, get_build_version
import platform_macos_builders
import subprocess
import shutil import shutil
import subprocess
import platform_macos_builders
from platform_methods import get_build_version, lipo
def generate_bundle(target, source, env): def generate_bundle(target, source, env):

View File

@ -1,10 +1,10 @@
import os import os
import sys import sys
from methods import print_error, detect_darwin_sdk_path, get_compiler_version, is_vanilla_clang
from platform_methods import detect_arch, detect_mvk
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from methods import detect_darwin_sdk_path, get_compiler_version, is_vanilla_clang, print_error
from platform_methods import detect_arch, detect_mvk
if TYPE_CHECKING: if TYPE_CHECKING:
from SCons.Script.SConscript import SConsEnvironment from SCons.Script.SConscript import SConsEnvironment
@ -107,7 +107,7 @@ def configure(env: "SConsEnvironment"):
env.Append(CCFLAGS=["-fobjc-arc"]) env.Append(CCFLAGS=["-fobjc-arc"])
if not "osxcross" in env: # regular native build if "osxcross" not in env: # regular native build
if env["macports_clang"] != "no": if env["macports_clang"] != "no":
mpprefix = os.environ.get("MACPORTS_PREFIX", "/opt/local") mpprefix = os.environ.get("MACPORTS_PREFIX", "/opt/local")
mpclangver = env["macports_clang"] mpclangver = env["macports_clang"]

View File

@ -6,9 +6,10 @@ Import("env")
# The HTTP server "targets". Run with "scons p=web serve", or "scons p=web run" # The HTTP server "targets". Run with "scons p=web serve", or "scons p=web run"
if "serve" in COMMAND_LINE_TARGETS or "run" in COMMAND_LINE_TARGETS: if "serve" in COMMAND_LINE_TARGETS or "run" in COMMAND_LINE_TARGETS:
from serve import serve
import os import os
from serve import serve
port = os.environ.get("GODOT_WEB_TEST_PORT", 8060) port = os.environ.get("GODOT_WEB_TEST_PORT", 8060)
try: try:
port = int(port) port = int(port)

View File

@ -1,18 +1,19 @@
import os import os
import sys import sys
from typing import TYPE_CHECKING
from emscripten_helpers import ( from emscripten_helpers import (
run_closure_compiler, add_js_externs,
create_engine_file,
add_js_libraries, add_js_libraries,
add_js_pre, add_js_pre,
add_js_externs, create_engine_file,
create_template_zip, create_template_zip,
get_template_zip_path, get_template_zip_path,
run_closure_compiler,
) )
from methods import print_warning, print_error, get_compiler_version
from SCons.Util import WhereIs from SCons.Util import WhereIs
from typing import TYPE_CHECKING
from methods import get_compiler_version, print_error, print_warning
if TYPE_CHECKING: if TYPE_CHECKING:
from SCons.Script.SConscript import SConsEnvironment from SCons.Script.SConscript import SConsEnvironment

View File

@ -1,4 +1,5 @@
import os, json import json
import os
from SCons.Util import WhereIs from SCons.Util import WhereIs
@ -24,13 +25,13 @@ def get_build_version():
import version import version
name = "custom_build" name = "custom_build"
if os.getenv("BUILD_NAME") != None: if os.getenv("BUILD_NAME") is not None:
name = os.getenv("BUILD_NAME") name = os.getenv("BUILD_NAME")
v = "%d.%d" % (version.major, version.minor) v = "%d.%d" % (version.major, version.minor)
if version.patch > 0: if version.patch > 0:
v += ".%d" % version.patch v += ".%d" % version.patch
status = version.status status = version.status
if os.getenv("GODOT_VERSION_STATUS") != None: if os.getenv("GODOT_VERSION_STATUS") is not None:
status = str(os.getenv("GODOT_VERSION_STATUS")) status = str(os.getenv("GODOT_VERSION_STATUS"))
v += ".%s.%s" % (status, name) v += ".%s.%s" % (status, name)
return v return v

View File

@ -1,13 +1,13 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from http.server import HTTPServer, SimpleHTTPRequestHandler, test # type: ignore
from pathlib import Path
import os
import sys
import argparse import argparse
import contextlib import contextlib
import os
import socket import socket
import subprocess import subprocess
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler, test # type: ignore
from pathlib import Path
# See cpython GH-17851 and GH-17864. # See cpython GH-17851 and GH-17864.

View File

@ -4,6 +4,7 @@ Import("env")
import os import os
from pathlib import Path from pathlib import Path
import platform_windows_builders import platform_windows_builders
sources = [] sources = []

View File

@ -1,12 +1,12 @@
import methods
import os import os
import subprocess import subprocess
import sys import sys
from methods import print_warning, print_error
from platform_methods import detect_arch
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import methods
from methods import print_error, print_warning
from platform_methods import detect_arch
if TYPE_CHECKING: if TYPE_CHECKING:
from SCons.Script.SConscript import SConsEnvironment from SCons.Script.SConscript import SConsEnvironment
@ -178,7 +178,7 @@ def get_opts():
caller_frame = inspect.stack()[1] caller_frame = inspect.stack()[1]
caller_script_dir = os.path.dirname(os.path.abspath(caller_frame[1])) caller_script_dir = os.path.dirname(os.path.abspath(caller_frame[1]))
d3d12_deps_folder = os.path.join(caller_script_dir, "bin", "build_deps") d3d12_deps_folder = os.path.join(caller_script_dir, "bin", "build_deps")
except: # Give up. except Exception: # Give up.
d3d12_deps_folder = "" d3d12_deps_folder = ""
return [ return [
@ -523,7 +523,7 @@ def configure_msvc(env: "SConsEnvironment", vcvars_msvc_config):
env.Append(CXXFLAGS=["/bigobj"]) env.Append(CXXFLAGS=["/bigobj"])
# PIX # PIX
if not env["arch"] in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]): if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
env["use_pix"] = False env["use_pix"] = False
if env["use_pix"]: if env["use_pix"]:
@ -750,7 +750,7 @@ def configure_mingw(env: "SConsEnvironment"):
env.Append(LIBS=["dxgi", "dxguid"]) env.Append(LIBS=["dxgi", "dxguid"])
# PIX # PIX
if not env["arch"] in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]): if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
env["use_pix"] = False env["use_pix"] = False
if env["use_pix"]: if env["use_pix"]:

View File

@ -1,8 +1,8 @@
"""Functions used to generate source files during build time""" """Functions used to generate source files during build time"""
import os import os
from detect import get_mingw_bin_prefix
from detect import try_cmd from detect import get_mingw_bin_prefix, try_cmd
def make_debug_mingw(target, source, env): def make_debug_mingw(target, source, env):

View File

@ -1,10 +1,7 @@
import os import os
import sys
import json
import platform import platform
import uuid
import functools
import subprocess import subprocess
import methods import methods
# NOTE: The multiprocessing module is not compatible with SCons due to conflict on cPickle # NOTE: The multiprocessing module is not compatible with SCons due to conflict on cPickle
@ -47,14 +44,14 @@ def get_build_version(short):
import version import version
name = "custom_build" name = "custom_build"
if os.getenv("BUILD_NAME") != None: if os.getenv("BUILD_NAME") is not None:
name = os.getenv("BUILD_NAME") name = os.getenv("BUILD_NAME")
v = "%d.%d" % (version.major, version.minor) v = "%d.%d" % (version.major, version.minor)
if version.patch > 0: if version.patch > 0:
v += ".%d" % version.patch v += ".%d" % version.patch
status = version.status status = version.status
if not short: if not short:
if os.getenv("GODOT_VERSION_STATUS") != None: if os.getenv("GODOT_VERSION_STATUS") is not None:
status = str(os.getenv("GODOT_VERSION_STATUS")) status = str(os.getenv("GODOT_VERSION_STATUS"))
v += ".%s.%s" % (status, name) v += ".%s.%s" % (status, name)
return v return v
@ -86,7 +83,7 @@ def get_mvk_sdk_path(osname):
def int_or_zero(i): def int_or_zero(i):
try: try:
return int(i) return int(i)
except: except (TypeError, ValueError):
return 0 return 0
def ver_parse(a): def ver_parse(a):
@ -140,9 +137,8 @@ def detect_mvk(env, osname):
) )
for mvk_path in mvk_list: for mvk_path in mvk_list:
if mvk_path and os.path.isfile(os.path.join(mvk_path, osname + "/libMoltenVK.a")): if mvk_path and os.path.isfile(os.path.join(mvk_path, f"{osname}/libMoltenVK.a")):
mvk_found = True print(f"MoltenVK found at: {mvk_path}")
print("MoltenVK found at: " + mvk_path)
return mvk_path return mvk_path
return "" return ""

View File

@ -11,6 +11,19 @@ namespace_packages = true
explicit_package_bases = true explicit_package_bases = true
exclude = ["thirdparty/"] exclude = ["thirdparty/"]
[tool.black] [tool.ruff]
extend-exclude = ["thirdparty"]
extend-include = ["SConstruct", "SCsub"]
line-length = 120 line-length = 120
extend-exclude = ".*thirdparty/.*" target-version = "py37"
[tool.ruff.lint]
extend-select = [
"I", # isort
]
[tool.ruff.lint.per-file-ignores]
"{SConstruct,SCsub}" = [
"E402", # Module level import not at top of file
"F821", # Undefined name
]

View File

@ -4,7 +4,6 @@ Import("env")
import default_theme_builders import default_theme_builders
env.add_source_files(env.scene_sources, "*.cpp") env.add_source_files(env.scene_sources, "*.cpp")
SConscript("icons/SCsub") SConscript("icons/SCsub")

View File

@ -4,7 +4,6 @@ Import("env")
import default_theme_icons_builders import default_theme_icons_builders
env["BUILDERS"]["MakeDefaultThemeIconsBuilder"] = Builder( env["BUILDERS"]["MakeDefaultThemeIconsBuilder"] = Builder(
action=env.Run(default_theme_icons_builders.make_default_theme_icons_action), action=env.Run(default_theme_icons_builders.make_default_theme_icons_action),
suffix=".h", suffix=".h",

View File

@ -1,11 +1,11 @@
"""Functions used to generate scu build source files during build time """Functions used to generate scu build source files during build time"""
"""
import glob, os import glob
import math import math
from methods import print_error import os
from pathlib import Path from pathlib import Path
from os.path import normpath, basename
from methods import print_error
base_folder_path = str(Path(__file__).parent) + "/" base_folder_path = str(Path(__file__).parent) + "/"
base_folder_only = os.path.basename(os.path.normpath(base_folder_path)) base_folder_only = os.path.basename(os.path.normpath(base_folder_path))
@ -25,7 +25,7 @@ def clear_out_stale_files(output_folder, extension, fresh_files):
for file in glob.glob(output_folder + "/*." + extension): for file in glob.glob(output_folder + "/*." + extension):
file = Path(file) file = Path(file)
if not file in fresh_files: if file not in fresh_files:
# print("removed stale file: " + str(file)) # print("removed stale file: " + str(file))
os.remove(file) os.remove(file)
@ -56,7 +56,7 @@ def find_files_in_folder(folder, sub_folder, include_list, extension, sought_exc
li = '#include "' + folder + "/" + sub_folder_slashed + file + '"' li = '#include "' + folder + "/" + sub_folder_slashed + file + '"'
if not simple_name in sought_exceptions: if simple_name not in sought_exceptions:
include_list.append(li) include_list.append(li)
else: else:
found_exceptions.append(li) found_exceptions.append(li)
@ -78,9 +78,9 @@ def write_output_file(file_count, include_list, start_line, end_line, output_fol
file_text = "" file_text = ""
for l in range(start_line, end_line): for i in range(start_line, end_line):
if l < len(include_list): if i < len(include_list):
line = include_list[l] line = include_list[i]
li = line + "\n" li = line + "\n"
file_text += li file_text += li
@ -221,7 +221,6 @@ def process_folder(folders, sought_exceptions=[], includes_per_scu=0, extension=
lines_per_file = max(lines_per_file, 1) lines_per_file = max(lines_per_file, 1)
start_line = 0 start_line = 0
file_number = 0
# These do not vary throughout the loop # These do not vary throughout the loop
output_folder = abs_main_folder + "/scu/" output_folder = abs_main_folder + "/scu/"

View File

@ -2,7 +2,7 @@ import json
import pytest import pytest
from gles3_builders import build_gles3_header, GLES3HeaderStruct from gles3_builders import GLES3HeaderStruct, build_gles3_header
@pytest.mark.parametrize( @pytest.mark.parametrize(

View File

@ -2,7 +2,7 @@ import json
import pytest import pytest
from glsl_builders import build_raw_header, RAWHeaderStruct, build_rd_header, RDHeaderStruct from glsl_builders import RAWHeaderStruct, RDHeaderStruct, build_raw_header, build_rd_header
@pytest.mark.parametrize( @pytest.mark.parametrize(