Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

Style: Integrate `pyupgrade` into Ruff linter

Thaddeus Crews492a1e0f1feb
diff --git a/SConstruct b/SConstruct
index fa07f3265e9..1ac334861cb 100644
--- a/SConstruct
+++ b/SConstruct
@@ -142,7 +142,7 @@ env["x86_libtheora_opt_gcc"] = False
env["x86_libtheora_opt_vc"] = False
# avoid issues when building with different versions of python out of the same directory
-env.SConsignFile(File("#.sconsign{0}.dblite".format(pickle.HIGHEST_PROTOCOL)).abspath)
+env.SConsignFile(File(f"#.sconsign{pickle.HIGHEST_PROTOCOL}.dblite").abspath)
# Build options
@@ -158,7 +158,7 @@ if profile:
opts = Variables(customs, ARGUMENTS)
# Target build options
-opts.Add((["platform", "p"], "Target platform (%s)" % "|".join(platform_list), ""))
+opts.Add((["platform", "p"], f"Target platform ({'|'.join(platform_list)})", ""))
opts.Add(
EnumVariable(
"target", "Compilation target", "editor", ["editor", "template_release", "template_debug"], ignorecase=2
@@ -637,8 +637,8 @@ if env.GetOption("num_jobs") == altered_num_jobs:
else:
safer_cpu_count = cpu_count if cpu_count <= 4 else cpu_count - 1
print(
- "Auto-detected %d CPU cores available for build parallelism. Using %d cores by default. You can override it with the `-j` or `num_jobs` arguments."
- % (cpu_count, safer_cpu_count)
+ f"Auto-detected {cpu_count} CPU cores available for build parallelism. Using {safer_cpu_count} cores by default. "
+ "You can override it with the `-j` or `num_jobs` arguments."
)
env.SetOption("num_jobs", safer_cpu_count)
diff --git a/core/input/input_builders.py b/core/input/input_builders.py
index 80ed9e2cfcf..2818bc4b747 100644
--- a/core/input/input_builders.py
+++ b/core/input/input_builders.py
@@ -48,9 +48,7 @@ def make_default_controller_mappings(target, source, env):
guid = line_parts[0]
if guid in platform_mappings[current_platform]:
file.write(
- "// WARNING: DATABASE {} OVERWROTE PRIOR MAPPING: {} {}\n".format(
- src_path, current_platform, platform_mappings[current_platform][guid]
- )
+ f"// WARNING: DATABASE {src_path} OVERWROTE PRIOR MAPPING: {current_platform} {platform_mappings[current_platform][guid]}\n"
)
platform_mappings[current_platform][guid] = line
diff --git a/doc/tools/doc_status.py b/doc/tools/doc_status.py
index e51b35ca4c1..9bc3d062b4b 100755
--- a/doc/tools/doc_status.py
+++ b/doc/tools/doc_status.py
@@ -246,7 +246,7 @@ class ClassStatus:
output["comment"] = color("part_good", "ALL OK")
else:
output["url"] = color(
- "url", "https://docs.godotengine.org/en/latest/classes/class_{name}.html".format(name=self.name.lower())
+ "url", f"https://docs.godotengine.org/en/latest/classes/class_{self.name.lower()}.html"
)
if flags["s"] and not flags["g"] and self.is_ok():
@@ -442,7 +442,7 @@ if len(table) == 1 and flags["a"]:
sys.exit(0)
if len(table) > 2 or not flags["a"]:
- total_status.name = "Total = {0}".format(len(table) - 1)
+ total_status.name = f"Total = {len(table) - 1}"
out = total_status.make_output()
row = []
for column in table_columns:
diff --git a/doc/tools/make_rst.py b/doc/tools/make_rst.py
index 061c4954fd6..2433024070c 100755
--- a/doc/tools/make_rst.py
+++ b/doc/tools/make_rst.py
@@ -393,7 +393,7 @@ class State:
theme_item_name = theme_item.attrib["name"]
theme_item_data_name = theme_item.attrib["data_type"]
- theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name)
+ theme_item_id = f"{theme_item_data_name}_{theme_item_name}"
if theme_item_id in class_def.theme_items:
print_error(
f'{class_name}.xml: Duplicate theme property "{theme_item_name}" of type "{theme_item_data_name}".',
@@ -749,9 +749,7 @@ def main() -> None:
if not args.dry_run and args.lang != "en":
global writing_translation
writing_translation = True
- lang_file = os.path.join(
- os.path.dirname(os.path.realpath(__file__)), "..", "translations", "{}.po".format(args.lang)
- )
+ lang_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "translations", f"{args.lang}.po")
if os.path.exists(lang_file):
try:
import polib # type: ignore
@@ -2189,7 +2187,7 @@ def format_text_block(
# Default to the tag command name. This works by default for most tags,
# but method, member, and theme_item have special cases.
- ref_type = "_{}".format(tag_state.name)
+ ref_type = f"_{tag_state.name}"
if target_class_name in state.classes:
class_def = state.classes[target_class_name]
diff --git a/editor/editor_builders.py b/editor/editor_builders.py
index d9091f04636..d705160bdc6 100644
--- a/editor/editor_builders.py
+++ b/editor/editor_builders.py
@@ -91,8 +91,7 @@ def make_translations(target, source, env):
buffer = methods.get_buffer(mo_path)
except OSError as e:
methods.print_warning(
- "msgfmt execution failed, using .po file instead of .mo: path=%r; [%s] %s"
- % (path, e.__class__.__name__, e)
+ f"msgfmt execution failed, using .po file instead of .mo: path={path!r}; [{e.__class__.__name__}] {e}"
)
buffer = methods.get_buffer(path)
finally:
@@ -102,7 +101,7 @@ def make_translations(target, source, env):
except OSError as e:
# Do not fail the entire build if it cannot delete a temporary file.
methods.print_warning(
- "Could not delete temporary .mo file: path=%r; [%s] %s" % (mo_path, e.__class__.__name__, e)
+ f"Could not delete temporary .mo file: path={mo_path!r}; [{e.__class__.__name__}] {e}"
)
else:
buffer = methods.get_buffer(path)
diff --git a/methods.py b/methods.py
index e126be22341..1431e486248 100644
--- a/methods.py
+++ b/methods.py
@@ -10,9 +10,10 @@ import subprocess
import sys
import zlib
from collections import OrderedDict
+from collections.abc import Generator
from io import StringIO
from pathlib import Path
-from typing import Generator, TextIO, cast
+from typing import TextIO, cast
from misc.utility.color import print_error, print_info, print_warning
from platform_methods import detect_arch
@@ -46,7 +47,7 @@ def add_source_files_orig(self, sources, files, allow_gen=False):
for file in files:
obj = self.Object(file)
if obj in sources:
- print_warning('Object "{}" already included in environment sources.'.format(obj))
+ print_warning(f'Object "{obj}" already included in environment sources.')
continue
sources.append(obj)
@@ -344,7 +345,7 @@ def module_check_dependencies(self, module):
missing_deps = set()
required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else []
for dep in required_deps:
- opt = "module_{}_enabled".format(dep)
+ opt = f"module_{dep}_enabled"
if opt not in self or not self[opt] or not module_check_dependencies(self, dep):
missing_deps.add(dep)
@@ -654,7 +655,7 @@ def detect_darwin_sdk_path(platform, env):
if sdk_path:
env[var_name] = sdk_path
except (subprocess.CalledProcessError, OSError):
- print_error("Failed to find SDK path while running 'xcrun --sdk {} --show-sdk-path'.".format(sdk_name))
+ print_error(f"Failed to find SDK path while running 'xcrun --sdk {sdk_name} --show-sdk-path'.")
raise
@@ -1291,9 +1292,7 @@ def generate_vs_project(env, original_args, project_name="godot"):
itemlist[key] += [item]
for x in itemlist.keys():
- properties.append(
- "<ActiveProjectItemList_%s>;%s;</ActiveProjectItemList_%s>" % (x, ";".join(itemlist[x]), x)
- )
+ properties.append(f"<ActiveProjectItemList_{x}>;{';'.join(itemlist[x])};</ActiveProjectItemList_{x}>")
output = os.path.join("bin", f"godot{env['PROGSUFFIX']}")
# The modules_enabled.gen.h header containing the defines is only generated on build, and only for the most recently built
diff --git a/misc/utility/godot_gdb_pretty_print.py b/misc/utility/godot_gdb_pretty_print.py
index 13da9eb618b..cb1c24c15b2 100644
--- a/misc/utility/godot_gdb_pretty_print.py
+++ b/misc/utility/godot_gdb_pretty_print.py
@@ -38,7 +38,7 @@ class GodotStringNamePrinter:
if data == 0:
return ""
- return '"%s"' % data["name"]["_cowdata"]["_ptr"].string()
+ return f'"{data["name"]["_cowdata"]["_ptr"].string()}"'
# Hint that the object is string-like.
def display_hint(self):
@@ -118,7 +118,7 @@ class GodotVectorPrinter:
yield str(i), (ptr + i).dereference()
def to_string(self):
- return "%s [%d]" % (self.value.type.name, self.get_size())
+ return f"{self.value.type.name} [{self.get_size()}]"
# Hint that the object is array-like.
def display_hint(self):
@@ -145,7 +145,7 @@ class GodotLocalVectorPrinter:
yield str(i), (data + i).dereference()
def to_string(self):
- return "%s [%d]" % (self.value.type.name, self.value["count"])
+ return f"{self.value.type.name} [{self.value['count']}]"
# Hint that the object is array-like.
def display_hint(self):
diff --git a/modules/SCsub b/modules/SCsub
index 69dfadfa311..80407c5cef4 100644
--- a/modules/SCsub
+++ b/modules/SCsub
@@ -38,7 +38,7 @@ for name, path in env.module_list.items():
SConscript(base_path + "/SCsub")
if env.modules_sources:
- lib = env_modules.add_library("module_%s" % name, env.modules_sources)
+ lib = env_modules.add_library(f"module_{name}", env.modules_sources)
env.Prepend(LIBS=[lib])
if env["tests"]:
diff --git a/platform/android/detect.py b/platform/android/detect.py
index 6d9f3323a52..732043a4965 100644
--- a/platform/android/detect.py
+++ b/platform/android/detect.py
@@ -136,8 +136,7 @@ def configure(env: "SConsEnvironment"):
if get_min_sdk_version(env["ndk_platform"]) < get_min_target_api():
print_warning(
- "Minimum supported Android target api is %d. Forcing target api %d."
- % (get_min_target_api(), get_min_target_api())
+ f"Minimum supported Android target api is {get_min_target_api()}. Forcing target api {get_min_target_api()}."
)
env["ndk_platform"] = "android-" + str(get_min_target_api())
diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py
index ab733c4d2d5..49275f310b3 100644
--- a/platform/linuxbsd/detect.py
+++ b/platform/linuxbsd/detect.py
@@ -153,7 +153,7 @@ def configure(env: "SConsEnvironment"):
else:
env.Append(LINKFLAGS=["-fuse-ld=mold"])
else:
- env.Append(LINKFLAGS=["-fuse-ld=%s" % env["linker"]])
+ env.Append(LINKFLAGS=[f"-fuse-ld={env['linker']}"])
if env["use_coverage"]:
env.Append(CCFLAGS=["-ftest-coverage", "-fprofile-arcs"])
diff --git a/platform/web/detect.py b/platform/web/detect.py
index e1cc6eb45a8..869f4971938 100644
--- a/platform/web/detect.py
+++ b/platform/web/detect.py
@@ -115,7 +115,7 @@ def configure(env: "SConsEnvironment"):
# Minimum emscripten requirements.
if cc_semver < (6, 0, 1):
- print_error("The minimum Emscripten version to build Godot is 6.0.1, detected: %s.%s.%s" % cc_semver)
+ print_error("The minimum Emscripten version to build Godot is 6.0.1, detected: {}.{}.{}".format(*cc_semver))
sys.exit(255)
env.Append(LIBEMITTER=[library_emitter])
@@ -159,7 +159,7 @@ def configure(env: "SConsEnvironment"):
print_info("Forcing `initial_memory=64` as it is required for the web editor.")
env["initial_memory"] = 64
- env.Append(LINKFLAGS=["-sINITIAL_MEMORY=%sMB" % env["initial_memory"]])
+ env.Append(LINKFLAGS=[f"-sINITIAL_MEMORY={env['initial_memory']}MB"])
## Copy env variables.
env["ENV"] = os.environ
@@ -251,14 +251,14 @@ def configure(env: "SConsEnvironment"):
if env["javascript_eval"]:
env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"])
- env.Append(LINKFLAGS=["-s%s=%sKB" % ("STACK_SIZE", env["stack_size"])])
+ env.Append(LINKFLAGS=[f"-sSTACK_SIZE={env['stack_size']}KB"])
if env["threads"]:
# Thread support (via SharedArrayBuffer).
env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"])
env.Append(CCFLAGS=["-pthread"])
env.Append(LINKFLAGS=["-pthread"])
- env.Append(LINKFLAGS=["-sDEFAULT_PTHREAD_STACK_SIZE=%sKB" % env["default_pthread_stack_size"]])
+ env.Append(LINKFLAGS=[f"-sDEFAULT_PTHREAD_STACK_SIZE={env['default_pthread_stack_size']}KB"])
env.Append(LINKFLAGS=["-sPTHREAD_POOL_SIZE=\"Module['emscriptenPoolSize']||8\""])
env.Append(LINKFLAGS=["-sMAXIMUM_MEMORY=2048MB"])
if not env["dlink_enabled"]:
diff --git a/platform_methods.py b/platform_methods.py
index c0a91355a08..125afdf6a5f 100644
--- a/platform_methods.py
+++ b/platform_methods.py
@@ -51,8 +51,7 @@ def detect_arch():
def validate_arch(arch, platform_name, supported_arches):
if arch not in supported_arches:
methods.print_error(
- 'Unsupported CPU architecture "%s" for %s. Supported architectures are: %s.'
- % (arch, platform_name, ", ".join(supported_arches))
+ f'Unsupported CPU architecture "{arch}" for {platform_name}. Supported architectures are: {", ".join(supported_arches)}.'
)
sys.exit(255)
@@ -63,14 +62,14 @@ def get_build_version(short):
name = "custom_build"
if os.getenv("BUILD_NAME") is not None:
name = os.getenv("BUILD_NAME")
- v = "%d.%d" % (version.major, version.minor)
+ v = f"{version.major}.{version.minor}"
if version.patch > 0:
- v += ".%d" % version.patch
+ v += f".{version.patch}"
status = version.status
if not short:
if os.getenv("GODOT_VERSION_STATUS") is not None:
status = str(os.getenv("GODOT_VERSION_STATUS"))
- v += ".%s.%s" % (status, name)
+ v += f".{status}.{name}"
return v
diff --git a/pyproject.toml b/pyproject.toml
index 0effff75b43..a8caa39a1ef 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -27,13 +27,14 @@ fix = true
# legacy defaults.
select = ["E4", "E7", "E9", "F"]
extend-select = [
- "FA", # flake8-future-annotations.
- "I", # isort.
- "UP006", # Use {to} instead of {from} for type annotation.
- "UP007", # Use `X | Y` for type annotations.
- "UP037", # Remove quotes from type annotation.
+ "FA", # flake8-future-annotations.
+ "I", # isort.
+ "UP", # pyupgrade.
]
-extend-safe-fixes = ["FA", "UP006", "UP007"]
+ignore = [
+ "UP015", # Unnecessary mode argument.
+]
+extend-safe-fixes = ["ALL"]
[tool.ruff.lint.per-file-ignores]
"{SConstruct,SCsub}" = [
diff --git a/scu_builders.py b/scu_builders.py
index 090df81620b..49acbe57409 100644
--- a/scu_builders.py
+++ b/scu_builders.py
@@ -74,7 +74,7 @@ def write_output_file(file_count, include_list, start_line, end_line, output_fol
print_error(f'SCU: "{output_folder}" could not be created.')
return
if _verbose:
- print("SCU: Creating folder: %s" % output_folder)
+ print(f"SCU: Creating folder: {output_folder}")
file_text = ""
@@ -94,7 +94,7 @@ def write_output_file(file_count, include_list, start_line, end_line, output_fol
if not output_path.exists() or output_path.read_text() != file_text:
if _verbose:
- print("SCU: Generating: %s" % short_filename)
+ print(f"SCU: Generating: {short_filename}")
output_path.write_text(file_text, encoding="utf8")
elif _verbose:
print("SCU: Generation not needed for: " + short_filename)
@@ -262,7 +262,7 @@ def generate_scu_files(max_includes_per_scu):
global _max_includes_per_scu
_max_includes_per_scu = max_includes_per_scu
- print("SCU: Generating build files... (max includes per SCU: %d)" % _max_includes_per_scu)
+ print(f"SCU: Generating build files... (max includes per SCU: {_max_includes_per_scu})")
curr_folder = os.path.abspath("./")
@@ -444,6 +444,6 @@ def generate_scu_files(max_includes_per_scu):
os.chdir(curr_folder)
if _verbose:
- print("SCU: Processed folders: %s" % sorted(_scu_folders))
+ print(f"SCU: Processed folders: {sorted(_scu_folders)}")
return _scu_folders
diff --git a/servers/rendering/storage/make_ltc_lut.py b/servers/rendering/storage/make_ltc_lut.py
index 6cb91dabaf9..4ed71c353b5 100644
--- a/servers/rendering/storage/make_ltc_lut.py
+++ b/servers/rendering/storage/make_ltc_lut.py
@@ -3,14 +3,14 @@ def write_bytes(file, source):
buffer = binary.read()
buffer = buffer[148:] # skip .dds header
- file.write("0x{:02x}".format(buffer[0]))
+ file.write(f"0x{buffer[0]:02x}")
for byte in range(1, len(buffer)):
- file.write(",0x{:02x}".format(buffer[byte]))
+ file.write(f",0x{buffer[byte]:02x}")
def run(target, source, env):
with open(str(target[0]), "w", encoding="utf-8", newline="\n") as file:
- file.write('/* WARNING, THIS FILE WAS GENERATED BY THE "{}" SCRIPT, DO NOT EDIT */ \n\n'.format(source[0].name))
+ file.write(f'/* WARNING, THIS FILE WAS GENERATED BY THE "{source[0].name}" SCRIPT, DO NOT EDIT */ \n\n')
file.write(
"// LTC Lookup table for BRDF fitting by Eric Heitz (https://eheitzresearch.wordpress.com/415-2/) \n"