Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Ruff Pyupgrade Rules #1516

Merged
merged 4 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
rev: cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b # frozen: v5.0.0
hooks:
- id: check-yaml
- repo: https://github.com/shellcheck-py/shellcheck-py
rev: v0.10.0.1
rev: a23f6b85d0fdd5bb9d564e2579e678033debbdff # frozen: v0.10.0.1
hooks:
- id: shellcheck
args: [--exclude, SC1017]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.11.2
rev: bbc3dc1f890007061f18f17e2334f216ea9e5df7 # frozen: v1.14.1
hooks:
- id: mypy
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.6.8'
rev: '18ba2d02dcafd1cc608bd83eff6c17fb0108ca71' # frozen: v0.9.1
hooks:
- id: ruff
args: [--fix]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ Note: Visual Studio versions 2013 (not for all projects), 2015, 2017, 2019, and
With your admin PowerShell terminal:

```PowerShell
choco install python312
choco install python313
```

2. Open a PowerShell terminal as a normal user and check the python version:
Expand Down
9 changes: 4 additions & 5 deletions gvsbuild/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

from enum import Enum
from pathlib import Path
from typing import Dict, List

import typer

Expand Down Expand Up @@ -59,7 +58,7 @@ def __get_projects_to_build(opts):
return to_build


def __parse_extra_opts(extra_opts: List[str]) -> Dict[str, List[str]]:
def __parse_extra_opts(extra_opts: list[str]) -> dict[str, list[str]]:
if extra_opts is None:
return {}
parsed_opts = {}
Expand Down Expand Up @@ -102,7 +101,7 @@ class WinSdkVersion(str, Enum):


def build(
projects: List[str] = typer.Argument(..., help="The project to build"),
projects: list[str] = typer.Argument(..., help="The project to build"),
platform: Platform = typer.Option(Platform.x64, help="The platform to build for"),
configuration: Configuration = typer.Option(
Configuration.debug_optimized,
Expand Down Expand Up @@ -205,7 +204,7 @@ def build(
help="Command line options to pass to msbuild.",
rich_help_panel="Options to Pass to Build Systems",
),
skip: List[str] = typer.Option(
skip: list[str] = typer.Option(
None,
help="Project to avoid building, can be run multiple times.",
rich_help_panel="Skip and Cleanup Options",
Expand Down Expand Up @@ -314,7 +313,7 @@ def build(
help="Command line options to pass to cargo",
rich_help_panel="Options to Pass to Build Systems",
),
extra_opts: List[str] = typer.Option(
extra_opts: list[str] = typer.Option(
None,
help="Additional command line options to pass to specific project."
" Example: --extra_opts <project>:<option1>[;<option1>...]",
Expand Down
4 changes: 1 addition & 3 deletions gvsbuild/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@

"""gvsbuild deps print / .gv graph."""

from typing import List

import typer

# Verify we can import from the script directory
Expand Down Expand Up @@ -214,7 +212,7 @@ def deps(
invert: bool = typer.Option(
False, help="Invert the dependencies", rich_help_panel="Graphing Options"
),
skip: List[str] = typer.Option(
skip: list[str] = typer.Option(
None,
help="A comma separated list of projects not to graph",
rich_help_panel="Graphing Options",
Expand Down
3 changes: 1 addition & 2 deletions gvsbuild/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import json
from typing import List

import typer

from gvsbuild.utils.base_project import Project, ProjectType


def list_(
projects_names: List[str] = typer.Argument(None, help="The projects to list"),
projects_names: list[str] = typer.Argument(None, help="The projects to list"),
project_type: ProjectType = typer.Option(
None,
"--type",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sys

with open(sys.argv[1], "r") as f:
with open(sys.argv[1]) as f:
for line in f.readlines():
line = line.strip()
if line and not line.startswith("#"):
Expand Down
3 changes: 1 addition & 2 deletions gvsbuild/projects/ffmpeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ def build(self):
)
msys_path = Project.get_tool_path("msys2")
self.exec_vs(
r"%s\bash build\build.sh %s %s %s %s"
% (
r"{}\bash build\build.sh {} {} {} {}".format(
msys_path,
convert_to_msys(self.pkg_dir),
convert_to_msys(self.builder.gtk_dir),
Expand Down
7 changes: 1 addition & 6 deletions gvsbuild/projects/gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,7 @@ def build(self):
self.pop_location()

self.push_location(
r".\nmake\vs%s\%s\%s"
% (
self.builder.opts.vs_ver,
self.builder.opts.configuration,
self.builder.opts.platform,
)
rf".\nmake\vs{self.builder.opts.vs_ver}\{self.builder.opts.configuration}\{self.builder.opts.platform}"
)
self.install(r".\asprintf.dll bin")
self.install(r".\asprintf.pdb bin")
Expand Down
2 changes: 1 addition & 1 deletion gvsbuild/projects/gtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def make_all_mo(self):
self.builder.exec_cmd(cmd, working_dir=self._get_working_dir())
self.pop_location()

self.install(r".\COPYING share\doc\%s" % self.name)
self.install(rf".\COPYING share\doc\{self.name}")


@project_add
Expand Down
2 changes: 1 addition & 1 deletion gvsbuild/projects/libfido2.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,4 @@ def build(self):
cmake_params = f"-DWITH_ZLIB=ON -DCBOR_INCLUDE_DIRS={include_dirs} -DCRYPTO_INCLUDE_DIRS={include_dirs} -DZLIB_INCLUDE_DIRS={include_dirs} -DCBOR_LIBRARY_DIRS={lib_dirs} -DCRYPTO_LIBRARY_DIRS={lib_dirs} -DZLIB_LIBRARY_DIRS={lib_dirs} -DCBOR_BIN_DIRS={bin_dirs} -DCRYPTO_BIN_DIRS={bin_dirs} -DZLIB_BIN_DIRS={bin_dirs} -DCRYPTO_LIBRARIES=libcrypto {build_params}"

CmakeProject.build(self, cmake_params=cmake_params, use_ninja=True)
self.install(r"output\%s\static\* ." % (arch))
self.install(rf"output\{arch}\static\* .")
8 changes: 1 addition & 7 deletions gvsbuild/projects/libvpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,7 @@ def build(self):
msys_path = Project.get_tool_path("msys2")

self.exec_vs(
r"%s\bash ./configure --target=%s --prefix=%s %s"
% (
msys_path,
target,
convert_to_msys(self.builder.gtk_dir),
configure_options,
),
rf"{msys_path}\bash ./configure --target={target} --prefix={convert_to_msys(self.builder.gtk_dir)} {configure_options}",
add_path=msys_path,
)
self.exec_vs(r"make", add_path=msys_path)
Expand Down
7 changes: 1 addition & 6 deletions gvsbuild/projects/x264.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,7 @@ def build(self):
)
msys_path = Project.get_tool_path("msys2")
self.exec_vs(
r"%s\bash build\build.sh %s %s"
% (
msys_path,
convert_to_msys(self.builder.gtk_dir),
configuration,
),
rf"{msys_path}\bash build\build.sh {convert_to_msys(self.builder.gtk_dir)} {configuration}",
add_path=msys_path,
)

Expand Down
2 changes: 1 addition & 1 deletion gvsbuild/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def unpack(self):
env["CARGO_HOME"] = self.build_dir

toolchain = (
f'{self.version}-{"i686" if self.opts.x86 else "x86_64"}-pc-windows-msvc'
f"{self.version}-{'i686' if self.opts.x86 else 'x86_64'}-pc-windows-msvc"
)
subprocess.run(
f"{self.archive_file} --no-modify-path --default-toolchain {toolchain} -y",
Expand Down
2 changes: 1 addition & 1 deletion gvsbuild/utils/base_builders.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def make_single_gir(self, prj_name, prj_dir=None):
log.message(f"Unable to find detectenv-msvc.mak for {prj_name}")
return

cmd = f'nmake -f {prj_name}-introspection-msvc.mak CFG={self.builder.opts.configuration} PREFIX={self.builder.gtk_dir} PYTHON={Project.get_tool_executable("python")} install-introspection'
cmd = f"nmake -f {prj_name}-introspection-msvc.mak CFG={self.builder.opts.configuration} PREFIX={self.builder.gtk_dir} PYTHON={Project.get_tool_executable('python')} install-introspection"

self.push_location(b_dir)
self.exec_vs(cmd)
Expand Down
14 changes: 7 additions & 7 deletions gvsbuild/utils/base_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import re
import shutil
from enum import Enum
from typing import Dict, Generic, List, Tuple, TypeVar
from typing import Generic, TypeVar

from .simple_ui import log
from .utils import _rmtree_error_handler
Expand Down Expand Up @@ -138,13 +138,13 @@ def __init__(self, name, **kwargs):
# register version params for use from derived classes
self.version_params = version_params

_projects: List[P] = []
_names: List[str] = []
_dict: Dict[str, P] = {}
_projects: list[P] = []
_names: list[str] = []
_dict: dict[str, P] = {}
_ver_res = None
name_len = 0
# List of class/type to add, now not at import time but after some options are parsed
_reg_prj_list: List[Tuple[P, ProjectType]] = []
_reg_prj_list: list[tuple[P, ProjectType]] = []
# build option
opts = Options()

Expand Down Expand Up @@ -207,7 +207,7 @@ def exec_msbuild(self, cmd, configuration=None, add_path=None):
add_path=add_path,
)

def _msbuild_make_search_replace(self, org_platform):
def _msbuild_make_search_replace(self, org_platform: str) -> tuple[bytes, bytes]:
"""Return the search & replace strings (converted to bytes to update
the platform Toolset version (v140, v141, ...) to use a new compiler,
e.g. to use vs2017 solution's files for vs2019.
Expand All @@ -226,7 +226,7 @@ def _msbuild_make_search_replace(self, org_platform):
dst_platform = "143"
else:
dst_platform = f"{ver}0"
search = (">v%u</PlatformToolset>" % (org_platform,)).encode("utf-8")
search = f">v{org_platform}</PlatformToolset>".encode()
replace = f">v{dst_platform}</PlatformToolset>".encode()

return search, replace
Expand Down
56 changes: 13 additions & 43 deletions gvsbuild/utils/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,7 @@ def __init__(self, opts):
def _create_msbuild_opts(self, python):
rt = [f"/nologo /p:Platform={self.opts.platform}"]
if python:
rt.append(
'/p:PythonPath="%(python_dir)s" /p:PythonDir="%(python_dir)s"'
% {"python_dir": python}
)
rt.append(f'/p:PythonPath="{python}" /p:PythonDir="{python}"')

if log.verbose_on():
rt.append("/v:normal")
Expand Down Expand Up @@ -269,8 +266,7 @@ def __check_tools(self, opts):
# oops
cmd = "pacman -S " + " ".join(missing)
log.error_exit(
"Missing package(s) from msys2 installation, try with\n '%s'\nin a msys2 shell."
% (cmd,)
f"Missing package(s) from msys2 installation, try with\n '{cmd}'\nin a msys2 shell."
)

self.patch = msys_path / "usr" / "bin" / "patch.exe"
Expand Down Expand Up @@ -321,7 +317,7 @@ def restore_env(self, saved):
del self.vs_env[key]

def __dump_vs_loc(self):
vswhere = r"%s\Microsoft Visual Studio\Installer\vswhere.exe" % (
vswhere = r"{}\Microsoft Visual Studio\Installer\vswhere.exe".format(
os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
)
log.log("Trying to find Visual Studio installations ...")
Expand Down Expand Up @@ -537,7 +533,7 @@ def build(self, projects):
if self.opts.check_hash:
return

# List of all the project we can mark for build because of a dependend
# List of all the project we can mark for build because of a dependent
self.prj_to_mark = [x for x in Project._projects if x.is_project()]

self.prj_done = []
Expand All @@ -555,11 +551,7 @@ def build(self, projects):
if self.__build_one(p):
self.prj_skipped.append(p.name)
else:
msg = "%-*s (%.3f s)" % (
Project.name_len,
p.name,
time.time() - st,
)
msg = f"{p.name:{Project.name_len}} ({time.time() - st:.3f})"
self.prj_done.append(msg)
except KeyboardInterrupt:
traceback.print_exc()
Expand Down Expand Up @@ -601,8 +593,7 @@ def build(self, projects):
log.message(f" {p}")
miss += len(self.prj_dropped)

# Don't fool appveyor
log.error_exit("%u project(s) missing ;(" % (miss,))
log.error_exit("%d project(s) missing ;(")

log.close()

Expand Down Expand Up @@ -783,12 +774,7 @@ def __check_hash(self, proj):
hc = self.__hashfile(proj.archive_file)
if hc != proj.hash:
log.error_exit(
"Hash mismatch on %s:\n Calculated '%s'\n Expected '%s'\n"
% (
proj.archive_file,
hc,
proj.hash,
)
f"Hash mismatch on {proj.archive_file}:\n Calculated '{hc}'\n Expected '{proj.hash}'\n"
)
return True

Expand All @@ -807,21 +793,14 @@ def __download_progress(self, count, block_size, total_size):
if perc != self._old_perc:
perc = min(perc, 100)
self._old_perc = perc
sp = "%s (%u k) - %u%%" % (
self._downloading_file,
total_size / 1024,
self._old_perc,
)
sp = f"{self._downloading_file} ({total_size / 1024}k) - {self._old_perc:.0f}%"
print(sp, end="\r")
if len(sp) > self._old_print:
# Save the len to delete the line when we change file
self._old_print = len(sp)
else:
# Only the current, we don't know the size
sp = "%s - %u k" % (
self._downloading_file,
c_size / 1024,
)
sp = f"{self._downloading_file} - {c_size / 1024:.0f} k"
print(sp, end="\r")
if len(sp) > self._old_print:
self._old_print = len(sp)
Expand All @@ -846,14 +825,7 @@ def urlretrieve(self, url, filename, reporthook, ssl_ignore_cert=False):
msg = f"Opening {url} ..."
print(msg, end="\r")
with contextlib.closing(urlopen(url, None, context=ssl_ctx)) as fp:
print(
"%*s"
% (
len(msg),
"",
),
end="\r",
)
print(f"{'':>{len(msg)}}", end="\r")
headers = fp.info()

with open(filename, "wb") as tfp:
Expand All @@ -879,7 +851,7 @@ def urlretrieve(self, url, filename, reporthook, ssl_ignore_cert=False):

if size >= 0 and read < size:
raise ContentTooShortError(
"retrieval incomplete: got only %i out of %i bytes" % (read, size),
f"retrieval incomplete: got only {read} out of {size} bytes",
result,
)

Expand Down Expand Up @@ -929,9 +901,7 @@ def __download_one(self, proj):
raise
log.end()

print(
"%-*s" % (self._old_print, f"{proj.archive_file} - Download finished"),
)
print(f"{proj.archive_file:{self._old_print}} - Download finished")
return self.__check_hash(proj)

def __sub_vars(self, s):
Expand Down Expand Up @@ -989,7 +959,7 @@ def exec_cargo(
# set platform
rustup = os.path.join(cargo_home, "rustup.exe")
self.__execute(
f'{rustup} default {rust_version}-{"i686" if self.x86 else "x86_64"}-pc-windows-msvc',
f"{rustup} default {rust_version}-{'i686' if self.x86 else 'x86_64'}-pc-windows-msvc",
env=env,
)

Expand Down
Loading
Loading