Skip to content

Commit

Permalink
chore: move to ruff (#525)
Browse files Browse the repository at this point in the history
  • Loading branch information
mayeut authored Jan 4, 2025
1 parent c84d80e commit 591430d
Show file tree
Hide file tree
Showing 33 changed files with 284 additions and 284 deletions.
29 changes: 7 additions & 22 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,19 @@ repos:
- id: debug-statements
- id: end-of-file-fixer
exclude: ^cache/
- id: mixed-line-ending
- id: forbid-new-submodules
- id: trailing-whitespace

- repo: https://github.com/asottile/pyupgrade
rev: v3.19.1
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.5
hooks:
- id: pyupgrade
args: ["--py39-plus"]

- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black

- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
args: ["-a", "from __future__ import annotations"]
exclude: ^tests/integration/.*/src/.*pyx$

- repo: https://github.com/PyCQA/flake8
rev: 7.1.1
hooks:
- id: flake8
- id: ruff
args: ["--fix", "--show-fixes"]
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.14.0
rev: v1.14.1
hooks:
- id: mypy
exclude: ^tests/integration/.*/.*$
Expand Down
2 changes: 1 addition & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def test_dist(session: nox.Session) -> None:

def _test_dist(session: nox.Session, path: str, pattern: str) -> None:
(dist_path,) = Path(path).glob(pattern)
session.install(f"{str(dist_path)}[test]")
session.install(f"{dist_path!s}[test]")
session.run("pytest", "tests/unit")


Expand Down
45 changes: 36 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,6 @@ build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
# enable version inference

[tool.black]
target-version = ["py39", "py310", "py311", "py312", "py313"]
extend-exclude = "src/auditwheel/_vendor"

[tool.isort]
py_version = 39
profile = "black"
extend_skip_glob = "src/auditwheel/_vendor/**/*.py"

[tool.mypy]
follow_imports = "silent"
ignore_missing_imports = true
Expand All @@ -23,3 +14,39 @@ warn_unused_ignores = true
module = "auditwheel._vendor.*"
follow_imports = "skip"
ignore_errors = true

[tool.pytest.ini_options]
log_cli = true
log_cli_level = 20

[tool.ruff]
target-version = "py39"
exclude = ["src/auditwheel/_vendor"]

[tool.ruff.lint]
extend-select = [
"B", # flake8-bugbear
"I", # isort
"ARG", # flake8-unused-arguments
"C4", # flake8-comprehensions
"EM", # flake8-errmsg
"ICN", # flake8-import-conventions
"ISC", # flake8-implicit-str-concat
"G", # flake8-logging-format
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PL", # pylint
"PT", # flake8-pytest-style
"RET", # flake8-return
"RUF", # Ruff-specific
"SIM", # flake8-simplify
"TID251", # flake8-tidy-imports.banned-api
"UP", # pyupgrade
"YTT", # flake8-2020
"EXE", # flake8-executable
"PYI", # flake8-pyi
]
ignore = [
"ISC001", # Conflicts with formatter
"PLR", # Design related pylint codes
]
15 changes: 7 additions & 8 deletions scripts/calculate_symbol_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from __future__ import annotations

import argparse
import contextlib
import json
import os
import platform
Expand All @@ -32,16 +33,17 @@ def choose_policy(name, policies):
try:
return next(policy for policy in policies if policy["name"] == name)
except StopIteration:
raise RuntimeError(f"Unknown policy {name}")
msg = f"Unknown policy {name}"
raise RuntimeError(msg) from None


def find_library(library):
for p in LIBRARY_PATHS:
path = os.path.join(p, library)
if os.path.exists(path):
return path
else:
raise RuntimeError(f"Unknown library {library}")
msg = f"Unknown library {library}"
raise RuntimeError(msg)


def versionify(version_string):
Expand All @@ -67,11 +69,8 @@ def calculate_symbol_versions(libraries, symbol_versions, arch):
if section:
for _, verdef_iter in section.iter_versions():
for vernaux in verdef_iter:
for symbol_name in symbol_versions:
try:
name, version = vernaux.name.split("_", 1)
except ValueError:
pass
with contextlib.suppress(ValueError):
name, version = vernaux.name.split("_", 1)
if (
name in calculated_symbol_versions
and version != "PRIVATE"
Expand Down
10 changes: 0 additions & 10 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,3 @@ where = src
[options.entry_points]
console_scripts =
auditwheel = auditwheel.main:main

[tool:pytest]
log_cli = true
log_cli_level = 20

[flake8]
ignore = E203,W503
max-line-length = 88
exclude =
_vendor
2 changes: 1 addition & 1 deletion setup.py
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"test": ["pytest>=3.4", "jsonschema", "pypatchelf", "pretend", "docker"],
"coverage": ["pytest-cov"],
}
extras["develop"] = sum(extras.values(), [])
extras["coverage"] += extras["test"]
extras["develop"] = list({dep for deps in extras.values() for dep in deps})

setup(extras_require=extras)
3 changes: 2 additions & 1 deletion src/auditwheel/condatools.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ def __enter__(self):

def iter_files(self) -> list[str]:
if self.path is None:
raise ValueError("This function should be called from context manager")
msg = "This function should be called from context manager"
raise ValueError(msg)
files = os.path.join(self.path, "info", "files")
with open(files) as f:
return [line.strip() for line in f.readlines()]
3 changes: 2 additions & 1 deletion src/auditwheel/elfutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ def elf_read_dt_needed(fn: str) -> list[str]:
elf = ELFFile(f)
section = elf.get_section_by_name(".dynamic")
if section is None:
raise ValueError("Could not find soname in %s" % fn)
msg = f"Could not find soname in {fn}"
raise ValueError(msg)

for t in section.iter_tags():
if t.entry.d_tag == "DT_NEEDED":
Expand Down
6 changes: 2 additions & 4 deletions src/auditwheel/genericpkgctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,5 @@ def InGenericPkgCtx(
if out_path is not None:
raise NotImplementedError()
return InCondaPkgCtx(in_path)

raise ValueError(
"Invalid package: %s. File formats supported: " ".whl, .tar.bz2" % in_path
)
msg = f"Invalid package: {in_path}. File formats supported: .whl, .tar.bz2"
raise ValueError(msg)
35 changes: 12 additions & 23 deletions src/auditwheel/lddtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,12 @@ def parse_ld_paths(str_ldpaths: str, path: str, root: str = "") -> list[str]:
for ldpath in str_ldpaths.split(":"):
if ldpath == "":
# The ldso treats "" paths as $PWD.
ldpath = os.getcwd()
ldpath_ = os.getcwd()
elif "$ORIGIN" in ldpath:
ldpath = ldpath.replace("$ORIGIN", os.path.dirname(os.path.abspath(path)))
ldpath_ = ldpath.replace("$ORIGIN", os.path.dirname(os.path.abspath(path)))
else:
ldpath = root + ldpath
ldpaths.append(normpath(ldpath))
ldpath_ = root + ldpath
ldpaths.append(normpath(ldpath_))
return [p for p in dedupe(ldpaths) if os.path.isdir(p)]


Expand Down Expand Up @@ -140,8 +140,8 @@ def parse_ld_so_conf(ldso_conf: str, root: str = "/", _first: bool = True) -> li
try:
log.debug("%sparse_ld_so_conf(%s)", dbg_pfx, ldso_conf)
with open(ldso_conf) as f:
for line in f.readlines():
line = line.split("#", 1)[0].strip()
for input_line in f.readlines():
line = input_line.split("#", 1)[0].strip()
if not line:
continue
if line.startswith("include "):
Expand Down Expand Up @@ -242,15 +242,7 @@ def compatible_elfs(elf1: ELFFile, elf2: ELFFile) -> bool:
"""
osabis = frozenset(e.header["e_ident"]["EI_OSABI"] for e in (elf1, elf2))
compat_sets = (
frozenset(
"ELFOSABI_%s" % x
for x in (
"NONE",
"SYSV",
"GNU",
"LINUX",
)
),
frozenset(f"ELFOSABI_{x}" for x in ("NONE", "SYSV", "GNU", "LINUX")),
)
return (
(len(osabis) == 1 or any(osabis.issubset(x) for x in compat_sets))
Expand Down Expand Up @@ -302,8 +294,7 @@ def lddtree(
ldpaths: dict[str, list[str]] | None = None,
display: str | None = None,
exclude: frozenset[str] = frozenset(),
_first: bool = True,
_all_libs: dict = {},
_all_libs: dict | None = None,
) -> dict:
"""Parse the ELF dependency tree of the specified file
Expand All @@ -324,8 +315,6 @@ def lddtree(
The path to show rather than ``path``
exclude
List of soname (DT_NEEDED) to exclude from the tree
_first
Recursive use only; is this the first ELF?
_all_libs
Recursive use only; dict of all libs we've seen
Expand All @@ -350,7 +339,8 @@ def lddtree(
if not ldpaths:
ldpaths = load_ld_paths().copy()

if _first:
_first = _all_libs is None
if _all_libs is None:
_all_libs = {}

ret: dict[str, Any] = {
Expand All @@ -363,7 +353,7 @@ def lddtree(
"libs": _all_libs,
}

log.debug("lddtree(%s)" % path)
log.debug("lddtree(%s)", path)

with open(path, "rb") as f:
elf = ELFFile(f)
Expand Down Expand Up @@ -407,7 +397,7 @@ def lddtree(
runpaths = parse_ld_paths(t.runpath, path=path, root=root)
elif t.entry.d_tag == "DT_NEEDED":
if any(fnmatch(t.needed, e) for e in exclude):
log.info(f"Excluding {t.needed}")
log.info("Excluding %s", t.needed)
else:
libs.append(t.needed)
if runpaths:
Expand Down Expand Up @@ -457,7 +447,6 @@ def lddtree(
ldpaths,
display=fullpath,
exclude=exclude,
_first=False,
_all_libs=_all_libs,
)
_all_libs[lib]["needed"] = lret["needed"]
Expand Down
4 changes: 1 addition & 3 deletions src/auditwheel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,4 @@ def main() -> int | None:
p.print_help()
return None

rval = args.func(args, p)

return rval
return args.func(args, p)
3 changes: 2 additions & 1 deletion src/auditwheel/main_lddtree.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import argparse
import logging

logger = logging.getLogger(__name__)
Expand All @@ -12,7 +13,7 @@ def configure_subparser(sub_parsers):
p.set_defaults(func=execute)


def execute(args, p):
def execute(args, p: argparse.ArgumentParser): # noqa: ARG001
import json

from .lddtree import lddtree
Expand Down
Loading

0 comments on commit 591430d

Please sign in to comment.