Skip to content

chore(linters): Introduce ruff and fix issues #831

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

Merged
merged 26 commits into from
Apr 5, 2025
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
7e1dd4f
chore(linters): Introduce ruff and fix issues
MaxymVlasov Feb 27, 2025
9430c1a
Merge branch 'master' into introduce_ruff
MaxymVlasov Mar 25, 2025
8dc8451
Apply review suggestions
MaxymVlasov Mar 25, 2025
8c3d385
Address review suggestions
MaxymVlasov Mar 25, 2025
53bb73f
Address review suggestions
MaxymVlasov Mar 25, 2025
8831b60
decrease diff
MaxymVlasov Mar 25, 2025
665d46c
Adress review comments
MaxymVlasov Mar 25, 2025
87273be
Discard changes to tests/pytest/terraform_docs_replace_test.py
MaxymVlasov Mar 25, 2025
fa302b0
Discard changes to src/pre_commit_terraform/terraform_docs_replace.py
MaxymVlasov Mar 25, 2025
f74ef59
Disable ruff for deprecated hook
MaxymVlasov Mar 25, 2025
e3c1272
Discard changes to src/pre_commit_terraform/__main__.py
MaxymVlasov Mar 25, 2025
71e794e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 25, 2025
b309d69
Address review suggestions and DOC501
MaxymVlasov Mar 25, 2025
948a36d
fix tests
MaxymVlasov Mar 25, 2025
7765818
Merge branch 'master' into introduce_ruff
MaxymVlasov Mar 26, 2025
51d9a93
Merge branch 'master' into introduce_ruff
MaxymVlasov Mar 26, 2025
bd24ee0
Merge branch 'master' into introduce_ruff
MaxymVlasov Mar 26, 2025
8384a66
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Mar 26, 2025
460031a
Merge branch 'master' into introduce_ruff
MaxymVlasov Mar 27, 2025
49f5087
Merge branch 'master' into introduce_ruff
MaxymVlasov Apr 3, 2025
593fe3d
Implement review suggestions and fix leftovers
MaxymVlasov Apr 3, 2025
585571d
fix tests by reverting PTH120
MaxymVlasov Apr 3, 2025
28aad2b
Merge branch 'master' into introduce_ruff
MaxymVlasov Apr 3, 2025
c6cd747
Discard changes to .gitignore
MaxymVlasov Apr 4, 2025
a6c9b5f
Address review suggestions regarding S404
MaxymVlasov Apr 4, 2025
641399c
fix violations
MaxymVlasov Apr 4, 2025
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
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ repos:
- id: shellcheck

# Python
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.4
hooks:
- id: ruff
args:
- --fix
- id: ruff-format
exclude: /terraform_docs_replace(_test)?\.py$

- repo: https://github.com/pre-commit/mirrors-mypy.git
rev: v1.15.0
hooks:
Expand Down
39 changes: 39 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Assume Python 3.9
target-version = "py39"

line-length = 79 # To decrease PR diff size

namespace-packages = ["src/pre_commit_terraform/", "tests/pytest/"]

[format]
quote-style = "single"

[lint.flake8-quotes]
inline-quotes = "single"

[lint.pydocstyle]
convention = "pep257"

[lint]
select = ["ALL"]
preview = true
ignore = [
"CPY001", # Missing copyright notice at top of file
]

[lint.isort]
# force-single-line = true # To decrease PR diff size
lines-after-imports = 2

[lint.flake8-pytest-style]
parametrize-values-type = "tuple"

[lint.per-file-ignores]
# Ignore in the `tests/` directory.
"tests/**.py" = [
"S101", # Use of `assert` detected
"PLC2701", # We need import marked as internal files for testing
]

"src/pre_commit_terraform/terraform_docs_replace.py" = ["ALL"] # Deprecated hook
"tests/pytest/terraform_docs_replace_test.py" = ["ALL"] # Tests for deprecated hook
3 changes: 2 additions & 1 deletion src/pre_commit_terraform/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""A runpy-style CLI entry-point module."""

from sys import argv, exit as exit_with_return_code
from sys import argv
from sys import exit as exit_with_return_code

from ._cli import invoke_cli_app

Expand Down
18 changes: 12 additions & 6 deletions src/pre_commit_terraform/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,35 +18,41 @@ def invoke_cli_app(cli_args: list[str]) -> ReturnCodeType:

Includes initializing parsers of all the sub-apps and
choosing what to execute.

Returns:
ReturnCodeType: The return code of the app.

Raises:
PreCommitTerraformExit: If the app is exiting with error.
"""
root_cli_parser = initialize_argument_parser()
parsed_cli_args = root_cli_parser.parse_args(cli_args)
invoke_cli_app = cast_to(
# FIXME: attempt typing per https://stackoverflow.com/a/75666611/595220
CLIAppEntryPointCallableType,
# FIXME: attempt typing per https://stackoverflow.com/a/75666611/595220 # noqa: TD001, TD002, TD003, FIX001, E501
'CLIAppEntryPointCallableType',
parsed_cli_args.invoke_cli_app,
)

try:
return invoke_cli_app(parsed_cli_args)
except PreCommitTerraformExit as exit_err:
print(f'App exiting: {exit_err !s}', file=sys.stderr)
print(f'App exiting: {exit_err !s}', file=sys.stderr) # noqa: T201 FIXME
raise
except PreCommitTerraformRuntimeError as unhandled_exc:
print(
print( # noqa: T201 FIXME
f'App execution took an unexpected turn: {unhandled_exc !s}. '
'Exiting...',
file=sys.stderr,
)
return ReturnCode.ERROR
except PreCommitTerraformBaseError as unhandled_exc:
print(
print( # noqa: T201 FIXME
f'A surprising exception happened: {unhandled_exc !s}. Exiting...',
file=sys.stderr,
)
return ReturnCode.ERROR
except KeyboardInterrupt as ctrl_c_exc:
print(
print( # noqa: T201 FIXME
f'User-initiated interrupt: {ctrl_c_exc !s}. Exiting...',
file=sys.stderr,
)
Expand Down
11 changes: 9 additions & 2 deletions src/pre_commit_terraform/_cli_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,22 @@ def attach_subcommand_parsers_to(root_cli_parser: ArgumentParser, /) -> None:
required=True,
)
for subcommand_module in SUBCOMMAND_MODULES:
subcommand_parser = subcommand_parsers.add_parser(subcommand_module.CLI_SUBCOMMAND_NAME)
subcommand_parser = subcommand_parsers.add_parser(
subcommand_module.CLI_SUBCOMMAND_NAME,
)
subcommand_parser.set_defaults(
invoke_cli_app=subcommand_module.invoke_cli_app,
)
subcommand_module.populate_argument_parser(subcommand_parser)


def initialize_argument_parser() -> ArgumentParser:
"""Return the root argument parser with sub-commands."""
"""Return the root argument parser with sub-commands.

Returns:
ArgumentParser: The root parser with sub-commands attached.

"""
root_cli_parser = ArgumentParser(prog=f'python -m {__package__ !s}')
attach_subcommand_parsers_to(root_cli_parser)
return root_cli_parser
Expand Down
6 changes: 3 additions & 3 deletions src/pre_commit_terraform/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ class PreCommitTerraformBaseError(Exception):


class PreCommitTerraformRuntimeError(
PreCommitTerraformBaseError,
RuntimeError,
PreCommitTerraformBaseError,
RuntimeError,
):
"""An exception representing a runtime error condition."""


class PreCommitTerraformExit(PreCommitTerraformBaseError, SystemExit):
class PreCommitTerraformExit(PreCommitTerraformBaseError, SystemExit): # noqa: N818 FIXME
"""An exception for terminating execution from deep app layers."""
3 changes: 2 additions & 1 deletion src/pre_commit_terraform/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class CLISubcommandModuleProtocol(Protocol):
"""This constant contains a CLI."""

def populate_argument_parser(
self, subcommand_parser: ArgumentParser,
self,
subcommand_parser: ArgumentParser,
) -> None:
"""Run a module hook for populating the subcommand parser."""

Expand Down
43 changes: 25 additions & 18 deletions tests/pytest/_cli_test.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Tests for the high-level CLI entry point."""

from argparse import ArgumentParser, Namespace
import pytest

import pytest
from pre_commit_terraform import _cli_parsing as _cli_parsing_mod
from pre_commit_terraform._cli import invoke_cli_app
from pre_commit_terraform._errors import (
PreCommitTerraformExit,
PreCommitTerraformBaseError,
PreCommitTerraformExit,
PreCommitTerraformRuntimeError,
)
from pre_commit_terraform._structs import ReturnCode
Expand All @@ -23,7 +23,6 @@
@pytest.mark.parametrize(
('raised_error', 'expected_stderr'),
(
# pytest.param(PreCommitTerraformExit('sentinel'), 'App exiting: sentinel', id='app-exit'),
pytest.param(
PreCommitTerraformRuntimeError('sentinel'),
'App execution took an unexpected turn: sentinel. Exiting...',
Expand All @@ -42,21 +41,23 @@
),
)
def test_known_interrupts(
capsys: pytest.CaptureFixture[str],
expected_stderr: str,
monkeypatch: pytest.MonkeyPatch,
raised_error: BaseException,
capsys: pytest.CaptureFixture[str],
expected_stderr: str,
monkeypatch: pytest.MonkeyPatch,
raised_error: BaseException,
) -> None:
"""Check that known interrupts are turned into return code 1."""

class CustomCmdStub:
CLI_SUBCOMMAND_NAME = 'sentinel'

def populate_argument_parser(
self, subcommand_parser: ArgumentParser,
def populate_argument_parser( # noqa: PLR6301
self,
subcommand_parser: ArgumentParser, # noqa: ARG002
) -> None:
return None

def invoke_cli_app(self, parsed_cli_args: Namespace) -> ReturnCodeType:
def invoke_cli_app(self, parsed_cli_args: Namespace) -> ReturnCodeType: # noqa: PLR6301, ARG002
raise raised_error

monkeypatch.setattr(
Expand All @@ -65,35 +66,41 @@ def invoke_cli_app(self, parsed_cli_args: Namespace) -> ReturnCodeType:
[CustomCmdStub()],
)

assert ReturnCode.ERROR == invoke_cli_app(['sentinel'])
assert invoke_cli_app(['sentinel']) == ReturnCode.ERROR

captured_outputs = capsys.readouterr()
assert captured_outputs.err == f'{expected_stderr !s}\n'


def test_app_exit(
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Check that an exit exception is re-raised."""

class CustomCmdStub:
CLI_SUBCOMMAND_NAME = 'sentinel'

def populate_argument_parser(
self, subcommand_parser: ArgumentParser,
def populate_argument_parser( # noqa: PLR6301
self,
subcommand_parser: ArgumentParser, # noqa: ARG002
) -> None:
return None

def invoke_cli_app(self, parsed_cli_args: Namespace) -> ReturnCodeType:
raise PreCommitTerraformExit('sentinel')
def invoke_cli_app( # noqa: PLR6301
self,
parsed_cli_args: Namespace, # noqa: ARG002
) -> ReturnCodeType:
err = 'sentinel'
raise PreCommitTerraformExit(err)

monkeypatch.setattr(
_cli_parsing_mod,
'SUBCOMMAND_MODULES',
[CustomCmdStub()],
)

with pytest.raises(PreCommitTerraformExit, match='^sentinel$'):
with pytest.raises(PreCommitTerraformExit, match=r'^sentinel$'):
invoke_cli_app(['sentinel'])

captured_outputs = capsys.readouterr()
Expand Down
Loading