Skip to content

Commit

Permalink
chore: move to ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
mayeut committed Jan 1, 2024
1 parent 355e535 commit 3653fd8
Show file tree
Hide file tree
Showing 11 changed files with 218 additions and 177 deletions.
27 changes: 6 additions & 21 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,15 @@ repos:
- id: forbid-new-submodules
- id: trailing-whitespace

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

- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.12.1
hooks:
- id: black

- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8

- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
args: ["-a", "from __future__ import annotations"]
- id: ruff
args: ["--fix", "--show-fixes"]
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
hooks:
- id: mypy
exclude: docs|src/pybase64/__main__.py|conftest.py|tests|setup.py
exclude: docs|conftest.py|tests
6 changes: 1 addition & 5 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python3
#
# pybase64 documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 29 22:06:28 2017.
#
Expand Down Expand Up @@ -63,9 +61,7 @@
# |version| and |release|, also used in various other places throughout the
# built documents.
# Get version
_version = runpy.run_path(os.path.join(here, "..", "src", "pybase64", "_version.py"))[
"__version__"
]
_version = runpy.run_path(os.path.join(here, "..", "src", "pybase64", "_version.py"))["__version__"]
# The short X.Y version.
version = _version
# The full version, including alpha/beta/rc tags.
Expand Down
10 changes: 10 additions & 0 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ def remove_extension(session: nox.Session, in_place: bool = False) -> None:
assert removed


@nox.session(python="3.12")
def develop(session: nox.Session) -> None:
"""create venv for dev."""
session.install("-r", "requirements-test.txt")
# make extension mandatory by exporting CIBUILDWHEEL=1
env = {"CIBUILDWHEEL": "1"}
update_env_macos(session, env)
session.install("-e", ".", env=env)


@nox.session(python=ALL_PYTHON)
def test(session: nox.Session) -> None:
"""Run tests."""
Expand Down
36 changes: 34 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,40 @@ test-requires = "-r requirements-test.txt"
test-command = "pytest {project}/tests"
build-verbosity = 1

[tool.isort]
profile = "black"
[tool.ruff]
target-version = "py37"
line-length = 100

[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 = [
"PLR", # Design related pylint codes
]

[tool.ruff.lint.flake8-tidy-imports.banned-api]
"typing.Callable".msg = "Use collections.abc.Callable instead."
"typing.Sequence".msg = "Use collections.abc.Sequence instead."

[tool.mypy]
python_version = "3.7"
Expand Down
2 changes: 0 additions & 2 deletions setup.cfg

This file was deleted.

65 changes: 32 additions & 33 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
from __future__ import annotations

import sys

if sys.version_info[:2] < (3, 7):
raise RuntimeError("Python version >= 3.7 required.")

import logging
import os
import platform as platform_module
import shutil
import subprocess
import sys
import sysconfig
from contextlib import contextmanager
from pathlib import Path
from typing import Generator

from setuptools import Extension, find_packages, setup
from setuptools.command.build_ext import build_ext
Expand All @@ -26,7 +23,7 @@
log = logging.getLogger("pybase64-setup")

# Get version
version_dict = {}
version_dict: dict[str, object] = {}
exec(HERE.joinpath("src", "pybase64", "_version.py").read_text(), {}, version_dict)
version = version_dict["__version__"]

Expand Down Expand Up @@ -61,26 +58,26 @@
)


def get_cmake_extra_config(plat_name, build_type):
def get_cmake_extra_config(plat_name: str | None, build_type: str) -> list[str]:
log.info("getting cmake extra config")
extra_config = []
machine = platform_module.machine().lower()
platform = sysconfig.get_platform()
archflags = os.environ.get("ARCHFLAGS", None)

log.info(f" machine: {machine}")
log.info(f" platform: {platform}")
log.info(f" plat_name: {plat_name}")
log.info(f" ARCHFLAGS: {archflags}")
log.info(f" CC: {os.environ.get('CC', None)}")
log.info(f" CFLAGS: {os.environ.get('CFLAGS', None)}")
log.info(f" LDFLAGS: {os.environ.get('LDFLAGS', None)}")
log.info(f" sysconfig CC: {sysconfig.get_config_var('CC')}")
log.info(f" sysconfig CCSHARED: {sysconfig.get_config_var('CCSHARED')}")
log.info(f" sysconfig CFLAGS: {sysconfig.get_config_var('CFLAGS')}")
log.info(f" sysconfig BASECFLAGS: {sysconfig.get_config_var('BASECFLAGS')}")
log.info(f" sysconfig OPT: {sysconfig.get_config_var('OPT')}")
log.info(f" sysconfig LDFLAGS: {sysconfig.get_config_var('LDFLAGS')}")
log.info(" machine: %s", machine)
log.info(" platform: %s", platform)
log.info(" plat_name: %s", plat_name)
log.info(" ARCHFLAGS: %s", archflags)
log.info(" CC: %s", os.environ.get("CC", None))
log.info(" CFLAGS: %s", os.environ.get("CFLAGS", None))
log.info(" LDFLAGS: %s", os.environ.get("LDFLAGS", None))
log.info(" sysconfig CC: %s", sysconfig.get_config_var("CC"))
log.info(" sysconfig CCSHARED: %s", sysconfig.get_config_var("CCSHARED"))
log.info(" sysconfig CFLAGS: %s", sysconfig.get_config_var("CFLAGS"))
log.info(" sysconfig BASECFLAGS: %s", sysconfig.get_config_var("BASECFLAGS"))
log.info(" sysconfig OPT: %s", sysconfig.get_config_var("OPT"))
log.info(" sysconfig LDFLAGS: %s", sysconfig.get_config_var("LDFLAGS"))

platform = plat_name or platform

Expand All @@ -89,7 +86,8 @@ def get_cmake_extra_config(plat_name, build_type):

if IS_WINDOWS:
if not platform.startswith("win"):
raise ValueError(f"Building {platform} is not supported on Windows")
msg = f"Building {platform} is not supported on Windows"
raise ValueError(msg)
# setup cross-compile
# assumes VS2019 or VS2022 will be used as the default generator
if platform == "win-amd64" and machine != "amd64":
Expand All @@ -110,35 +108,38 @@ def get_cmake_extra_config(plat_name, build_type):
"ppc64",
}
if not platform.startswith("macosx-"):
raise ValueError(f"Building {platform} is not supported on macOS")
msg = f"Building {platform} is not supported on macOS"
raise ValueError(msg)
_, _, platform_arch = platform.split("-")
if platform_arch.startswith(("universal", "fat")):
raise ValueError(f"multiple arch `{platform_arch}` is not supported")
msg = f"multiple arch `{platform_arch}` is not supported"
raise ValueError(msg)
configured_archs = {platform_arch}
if archflags:
flags = [arch.strip() for arch in archflags.strip().split() if arch.strip()]
for i in range(len(flags) - 1):
if flags[i] == "-arch":
configured_archs.add(flags[i + 1])
if len(configured_archs) > 1:
raise ValueError(f"multiple arch `{configured_archs}` is not supported")
msg = f"multiple arch `{configured_archs}` is not supported"
raise ValueError(msg)
arch = configured_archs.pop()
if arch in known_archs:
extra_config.append(f"-DCMAKE_OSX_ARCHITECTURES={arch}")
else:
log.warning(f"`{arch}` is not a known value for CMAKE_OSX_ARCHITECTURES")
log.warning("`%s` is not a known value for CMAKE_OSX_ARCHITECTURES", arch)

return extra_config


def cmake(*args):
def cmake(*args: str) -> None:
args_string = " ".join(f"'{arg}'" for arg in args)
log.info(f"running cmake {args_string}")
log.info("running cmake %s", args_string)
subprocess.run(["cmake", *args], check=True)


@contextmanager
def base64_build(plat_name):
def base64_build(plat_name: str | None) -> Generator[None, None, None]:
source_dir = HERE / "base64"
build_dir = HERE / ".base64_build"
build_type = "Release"
Expand All @@ -160,9 +161,7 @@ def base64_build(plat_name):
cmake(*config_options)
cmake("--build", str(build_dir), "--config", build_type, "--verbose")
if IS_WINDOWS:
shutil.copyfile(
build_dir / build_type / "base64.lib", build_dir / "base64.lib"
)
shutil.copyfile(build_dir / build_type / "base64.lib", build_dir / "base64.lib")
except Exception:
if not OPTIONAL_EXTENSION:
raise
Expand All @@ -174,7 +173,7 @@ def base64_build(plat_name):


class BuildExt(build_ext):
def finalize_options(self):
def finalize_options(self) -> None:
if "-coverage" in os.environ.get("CFLAGS", "").split():
plat_name = getattr(self, "plat_name", None) or sysconfig.get_platform()
temp_name = f"coverage-{plat_name}-{sys.implementation.cache_tag}"
Expand All @@ -184,7 +183,7 @@ def finalize_options(self):
self.build_temp = str(coverage_build)
super().finalize_options()

def run(self):
def run(self) -> None:
plat_name = getattr(self, "plat_name", None)
with base64_build(plat_name):
super().run()
Expand Down
2 changes: 1 addition & 1 deletion src/pybase64/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ._version import __version__

try:
from ._pybase64 import ( # noqa: F401
from ._pybase64 import (
_get_simd_name,
_get_simd_path,
b64decode,
Expand Down
Loading

0 comments on commit 3653fd8

Please sign in to comment.