Skip to content

Commit

Permalink
Switch to Ruff formatter (#1817)
Browse files Browse the repository at this point in the history
  • Loading branch information
messense authored Oct 25, 2023
1 parent 879bc88 commit a0d53b3
Show file tree
Hide file tree
Showing 8 changed files with 23 additions and 110 deletions.
39 changes: 0 additions & 39 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,45 +37,6 @@ jobs:
- name: cargo clippy
run: cargo clippy --tests --all-features -- -D warnings

black:
name: Black
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.x'
- uses: psf/[email protected]

ruff:
name: Ruff
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.x'
- run: pip install ruff
- run: ruff .

mypy:
name: Mypy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.x'
- run: pip install mypy
- run: mypy maturin

spellcheck:
name: Spellcheck
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: codespell-project/actions-codespell@master

cargo-deny:
name: Cargo deny
runs-on: ubuntu-latest
Expand Down
7 changes: 2 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,10 @@ repos:
(.*\.stdout)
)
- id: mixed-line-ending
- repo: https://github.com/psf/black
rev: 23.10.0
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.1
rev: v0.1.2
hooks:
- id: ruff-format
- id: ruff
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.6.1
Expand Down
36 changes: 9 additions & 27 deletions maturin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,12 @@ def get_config() -> Dict[str, str]:
return pyproject_toml.get("tool", {}).get("maturin", {})


def get_maturin_pep517_args(
config_settings: Optional[Mapping[str, Any]] = None
) -> List[str]:
def get_maturin_pep517_args(config_settings: Optional[Mapping[str, Any]] = None) -> List[str]:
build_args = config_settings.get("build-args") if config_settings else None
if build_args is None:
env_args = os.getenv("MATURIN_PEP517_ARGS", "")
if env_args:
print(
f"'MATURIN_PEP517_ARGS' is deprecated, use `--config-settings build-args='{env_args}'` instead."
)
print(f"'MATURIN_PEP517_ARGS' is deprecated, use `--config-settings build-args='{env_args}'` instead.")
args = shlex.split(env_args)
elif isinstance(build_args, str):
args = shlex.split(build_args)
Expand Down Expand Up @@ -91,9 +87,7 @@ def _build_wheel(
sys.stdout.buffer.write(result.stdout)
sys.stdout.flush()
if result.returncode != 0:
sys.stderr.write(
f"Error: command {command} returned non-zero exit status {result.returncode}\n"
)
sys.stderr.write(f"Error: command {command} returned non-zero exit status {result.returncode}\n")
sys.exit(1)
output = result.stdout.decode(errors="replace")
wheel_path = output.strip().splitlines()[-1]
Expand All @@ -112,9 +106,7 @@ def build_wheel(


# noinspection PyUnusedLocal
def build_sdist(
sdist_directory: str, config_settings: Optional[Mapping[str, Any]] = None
) -> str:
def build_sdist(sdist_directory: str, config_settings: Optional[Mapping[str, Any]] = None) -> str:
command = ["maturin", "pep517", "write-sdist", "--sdist-directory", sdist_directory]

print("Running `{}`".format(" ".join(command)))
Expand All @@ -123,18 +115,14 @@ def build_sdist(
sys.stdout.buffer.write(result.stdout)
sys.stdout.flush()
if result.returncode != 0:
sys.stderr.write(
f"Error: command {command} returned non-zero exit status {result.returncode}\n"
)
sys.stderr.write(f"Error: command {command} returned non-zero exit status {result.returncode}\n")
sys.exit(1)
output = result.stdout.decode(errors="replace")
return output.strip().splitlines()[-1]


# noinspection PyUnusedLocal
def get_requires_for_build_wheel(
config_settings: Optional[Mapping[str, Any]] = None
) -> List[str]:
def get_requires_for_build_wheel(config_settings: Optional[Mapping[str, Any]] = None) -> List[str]:
if get_config().get("bindings") == "cffi":
return ["cffi"]
else:
Expand All @@ -147,19 +135,15 @@ def build_editable(
config_settings: Optional[Mapping[str, Any]] = None,
metadata_directory: Optional[str] = None,
) -> str:
return _build_wheel(
wheel_directory, config_settings, metadata_directory, editable=True
)
return _build_wheel(wheel_directory, config_settings, metadata_directory, editable=True)


# Requirements to build an editable are the same as for a wheel
get_requires_for_build_editable = get_requires_for_build_wheel


# noinspection PyUnusedLocal
def get_requires_for_build_sdist(
config_settings: Optional[Mapping[str, Any]] = None
) -> List[str]:
def get_requires_for_build_sdist(config_settings: Optional[Mapping[str, Any]] = None) -> List[str]:
return []


Expand All @@ -170,9 +154,7 @@ def prepare_metadata_for_build_wheel(
print("Checking for Rust toolchain....")
is_cargo_installed = False
try:
output = subprocess.check_output(["cargo", "--version"]).decode(
"utf-8", "ignore"
)
output = subprocess.check_output(["cargo", "--version"]).decode("utf-8", "ignore")
if "cargo" in output:
is_cargo_installed = True
except (FileNotFoundError, SubprocessError):
Expand Down
21 changes: 5 additions & 16 deletions maturin/import_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ def find_spec(

return None

def _build_and_load(
self, fullname: str, cargo_toml: pathlib.Path
) -> ModuleSpec | None:
def _build_and_load(self, fullname: str, cargo_toml: pathlib.Path) -> ModuleSpec | None:
build_module(cargo_toml, bindings=self.bindings)
loader = Loader(fullname)
return importlib.util.spec_from_loader(fullname, loader)
Expand All @@ -98,10 +96,7 @@ def _is_cargo_project(cargo_toml: pathlib.Path, module_name: str) -> bool:
with open(cargo_toml, "rb") as f:
cargo = tomllib.load(f)
package_name = cargo.get("package", {}).get("name")
if (
package_name == module_name
or package_name.replace("-", "_") == module_name
):
if package_name == module_name or package_name.replace("-", "_") == module_name:
return True
return False

Expand All @@ -115,9 +110,7 @@ def generate_project(rust_file: pathlib.Path, bindings: str = "pyo3") -> pathlib
command: list[str] = ["maturin", "new", "-b", bindings, str(project_dir)]
result = subprocess.run(command, stdout=subprocess.PIPE)
if result.returncode != 0:
sys.stderr.write(
f"Error: command {command} returned non-zero exit status {result.returncode}\n"
)
sys.stderr.write(f"Error: command {command} returned non-zero exit status {result.returncode}\n")
raise ImportError("Failed to generate cargo project")

with open(rust_file) as f:
Expand All @@ -128,9 +121,7 @@ def generate_project(rust_file: pathlib.Path, bindings: str = "pyo3") -> pathlib
return project_dir


def build_module(
manifest_path: pathlib.Path, bindings: str | None = None, release: bool = False
) -> None:
def build_module(manifest_path: pathlib.Path, bindings: str | None = None, release: bool = False) -> None:
command = ["maturin", "develop", "-m", str(manifest_path)]
if bindings:
command.append("-b")
Expand All @@ -141,9 +132,7 @@ def build_module(
sys.stdout.buffer.write(result.stdout)
sys.stdout.flush()
if result.returncode != 0:
sys.stderr.write(
f"Error: command {command} returned non-zero exit status {result.returncode}\n"
)
sys.stderr.write(f"Error: command {command} returned non-zero exit status {result.returncode}\n")
raise ImportError("Failed to build module with maturin")


Expand Down
4 changes: 1 addition & 3 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def setup_pyodide(session: nox.Session):
external=True,
)
with open("repodata.json") as f:
emscripten_version = (
json.load(f)["info"]["platform"].split("_", 1)[1].replace("_", ".")
)
emscripten_version = json.load(f)["info"]["platform"].split("_", 1)[1].replace("_", ".")
append_to_github_env("EMSCRIPTEN_VERSION", emscripten_version)


Expand Down
4 changes: 1 addition & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ def finalize_options(self):
python_requires=">=3.7",
cmdclass={"bdist_wheel": bdist_wheel},
packages=["maturin"],
rust_extensions=[
RustBin("maturin", args=cargo_args, cargo_manifest_args=["--locked"])
],
rust_extensions=[RustBin("maturin", args=cargo_args, cargo_manifest_args=["--locked"])],
classifiers=[
"Topic :: Software Development :: Build Tools",
"Programming Language :: Rust",
Expand Down
8 changes: 2 additions & 6 deletions test-crates/cffi-mixed/cffi_mixed/line.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ def __init__(self, x1: float, y1: float, x2: float, y2: float):

def length(self) -> float:
"""Returns the length of the line."""
return math.sqrt(
(self.end.x - self.start.x) ** 2 + (self.end.y - self.start.y) ** 2
)
return math.sqrt((self.end.x - self.start.x) ** 2 + (self.end.y - self.start.y) ** 2)

def __str__(self) -> str:
return "Line from ({},{}) to ({},{})".format(
self.start.x, self.start.y, self.end.x, self.end.y
)
return "Line from ({},{}) to ({},{})".format(self.start.x, self.start.y, self.end.x, self.end.y)
14 changes: 3 additions & 11 deletions test-crates/update_readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,16 @@


def main():
root = Path(
subprocess.check_output(
["git", "rev-parse", "--show-toplevel"], text=True
).strip()
)
root = Path(subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip())

for path in FILES:
content = root.joinpath(path).read_text()

matcher = re.compile(
r"```\nUsage: maturin (\w+) (.*?)```", re.MULTILINE | re.DOTALL
)
matcher = re.compile(r"```\nUsage: maturin (\w+) (.*?)```", re.MULTILINE | re.DOTALL)

replaces = {}
for command, old in matcher.findall(content):
command_output = subprocess.check_output(
["cargo", "run", "--", command.lower(), "--help"], text=True
)
command_output = subprocess.check_output(["cargo", "run", "--", command.lower(), "--help"], text=True)
new = "Usage:" + command_output.strip().split("Usage:")[1] + "\n"
# Remove trailing whitespace
new = re.sub(" +\n", "\n", new)
Expand Down

0 comments on commit a0d53b3

Please sign in to comment.