Skip to content

Commit

Permalink
feat: abort earlier on errors (#31)
Browse files Browse the repository at this point in the history
This change does a few things:
  - raises exceptions immediately after an error is encountered
  - swaps out older linters for ruff
  - fixes some stability and performance issues raised from the new linter
  • Loading branch information
raddessi authored Jan 30, 2024
1 parent 3156977 commit 68b7030
Show file tree
Hide file tree
Showing 13 changed files with 271 additions and 249 deletions.
54 changes: 11 additions & 43 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pycqa/isort
rev: 5.13.2
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.14
hooks:
- id: isort
args: ["--profile", "black", "--filter-files"]
- id: ruff
args: [--fix]
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
hooks:
- id: prettier
require_serial: true # prettier can be too cpu heavy with `--all`

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
Expand All @@ -25,40 +32,6 @@ repos:
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]

- repo: https://github.com/psf/black
rev: 23.12.1
hooks:
- id: black
language_version: python3 # Should be a command that runs python3.6+

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8
hooks:
- id: prettier

- repo: https://github.com/PyCQA/bandit
rev: 1.7.6
hooks:
- id: bandit
entry: bandit -x 'conftest.py' -x 'tests/*'
types: [python]

- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade

- repo: https://github.com/pycqa/pydocstyle
rev: 6.3.0
hooks:
- id: pydocstyle
additional_dependencies: ["toml"]

- repo: https://github.com/asottile/yesqa
rev: v1.5.0
hooks:
- id: yesqa

- repo: https://github.com/commitizen-tools/commitizen
rev: v3.13.0
hooks:
Expand All @@ -70,8 +43,3 @@ repos:
hooks:
- id: darglint
entry: darglint --verbosity=2

- repo: https://github.com/pycqa/pylint
rev: v3.0.3
hooks:
- id: pylint
6 changes: 3 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Sphinx configuration."""
# pylint: disable=invalid-name
# ruff: noqa: INP001

from datetime import datetime
from datetime import datetime, timezone

project = "salt-gnupg-rotate"
author = "Ryan Addessi"
copyright = f"{datetime.now().year}, {author}" # pylint: disable=redefined-builtin
copyright = f"{datetime.now(tz=timezone.utc).year}, {author}" # noqa: A001


autodoc_typehints = "description"
Expand Down
120 changes: 70 additions & 50 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,27 +62,77 @@ requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

## Config for other tools

[tool.black]
[tool.ruff]
line-length = 88
exclude = '''
/(
\.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
| tests/fixtures
# The following are specific to Black, you probably don't want those.
| blib2to3
| tests/data
)/
'''
indent-width = 4
target-version = "py310"
exclude = [
".git",
".hg",
".mypy_cache",
".tox",
".venv",
"_build",
"buck-out",
"build",
"dist",
"tests/fixtures",
]

[tool.ruff.per-file-ignores]
"tests/*" = ["S101", "T201"]

[tool.ruff.lint]
select = ["ALL"]
ignore = [
"ANN",
"PL",
"TD002",
"TD003",
"FIX002",
"D203", # no-blank-line-before-class
"D213", # multi-line-summary-second-line
]

# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []

# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

[tool.ruff.lint.pep8-naming]
extend-ignore-names = ["test_*"]

[tool.ruff.lint.pydocstyle]
convention = "google"

[tool.ruff.format]
# Like Black, use double quotes for strings.
quote-style = "double"

# Like Black, indent with spaces, rather than tabs.
indent-style = "space"

# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false

# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"

# Enable auto-formatting of code examples in docstrings. Markdown,
# reStructuredText code/literal blocks and doctests are all supported.
#
# This is currently disabled by default, but it is planned for this
# to be opt-out in the future.
docstring-code-format = true

# Set the line length limit used when formatting code snippets in
# docstrings.
#
# This only has an effect when the `docstring-code-format` setting is
# enabled.
docstring-code-line-length = "dynamic"

[tool.commitizen]
name = "cz_conventional_commits"
Expand Down Expand Up @@ -110,16 +160,6 @@ fail_under = 100
# "configuration_files",
# ]

[tool.isort]
line_length = 88
not_skip = "__init__.py"
multi_line_output = 3
force_single_line = false
balanced_wrapping = true
default_section = "THIRDPARTY"
known_first_party = "salt_gnupg_rotate"
include_trailing_comma = true

[tool.mypy]
strict = true
warn_unreachable = true
Expand All @@ -130,26 +170,6 @@ show_error_context = true
ignore_missing_imports = true
# exclude = "somedir/"

[tool.pydocstyle]
convention = "google"
add_ignore = [
"D103", # handled by pylint
"D106", # handled by pylint
"D301", # for Click "\f" delimiters
]

[tool.pylint]

[tool.pylint.MASTER]
ignore-paths = []

[tool.pylint.'MESSAGES CONTROL']
disable = [
"duplicate-code", # not possible to disable inline currently
"fixme", # these get converted in to github issues
"import-error", # pre-commit does not have all the package deps available, yet
]

[tool.pytest.ini_options]
# `log_cli` would be AMAZING to enable but it currently conflicts with click's CliRunner
log_cli = false
Expand Down
9 changes: 6 additions & 3 deletions salt_gnupg_rotate/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,19 @@
)
@click.version_option(version=__version__, package_name=APP_NAME)
@click.help_option("-h", "--help")
def cli( # pylint: disable=too-many-arguments
def cli(
directory: str,
decryption_gpg_homedir: str,
encryption_gpg_homedir: str,
recipient: str,
log_level: str,
*,
write: bool,
) -> int:
"""Easily rotate gnupg encryption keys of fully or partially encrypted files.
r"""Easily rotate gnupg encryption keys of fully or partially encrypted files.
\f
Args:
directory: The directory path to search for files within that should be
re-encrypted
Expand Down Expand Up @@ -141,7 +144,7 @@ def cli( # pylint: disable=too-many-arguments
LOGGER.critical(err)
retcode = 3

except Exception as err: # pylint: disable=broad-except
except Exception as err: # noqa: BLE001
LOGGER.exception(err)
retcode = 9

Expand Down
8 changes: 3 additions & 5 deletions salt_gnupg_rotate/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Configuration."""

import os
from typing import List

from rich.console import Console

Expand All @@ -11,15 +10,14 @@
ENV_APP_NAME = "SALT_GNUPG_ROTATE"
CONSOLE = Console(stderr=True)
LOG_LEVEL: str = "info"
LOG_LEVELS: List[str] = list(
LOG_LEVELS: list[str] = list(
map(
str.lower,
[
level_name
# pylint: disable=protected-access
for _, level_name in sorted(logging._levelToName.items(), reverse=True)
for _, level_name in sorted(logging._levelToName.items(), reverse=True) # noqa: SLF001
],
)
),
)
DECRYPTION_GPG_HOMEDIR: str = os.getenv("GNUPGHOME", "~/.gnupg")
ENCRYPTION_GPG_HOMEDIR: str = os.getenv("GNUPGHOME", "~/.gnupg")
15 changes: 10 additions & 5 deletions salt_gnupg_rotate/logging_mixins.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Additions to the logging module."""

import logging
from typing import Any, Optional
from typing import Any

import rich.console
import rich.logging
Expand Down Expand Up @@ -31,8 +31,8 @@ def trace(self, message: str, *args: Any, **kwargs: Any) -> None:

def create_logger(
app_name: str,
log_level: Optional[str] = None,
console: Optional[rich.console.Console] = None,
log_level: str | None = None,
console: rich.console.Console | None = None,
) -> CustomLogger:
"""Set up the logger instance.
Expand All @@ -51,10 +51,15 @@ def create_logger(
logger = logging.getLogger(app_name)

if not isinstance(logger, CustomLogger):
raise TypeError(f"Logger instance not of type CustomLogger: {type(logger)}")
msg = f"Logger instance not of type CustomLogger: {type(logger)}"
raise TypeError(msg)

logger.addHandler(
rich.logging.RichHandler(rich_tracebacks=True, console=console, show_path=False)
rich.logging.RichHandler(
rich_tracebacks=True,
console=console,
show_path=False,
),
)

logger.setLevel((log_level or "NOTSET").upper())
Expand Down
21 changes: 9 additions & 12 deletions salt_gnupg_rotate/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Main code."""
import os
from pathlib import Path

# pylint: disable=import-error
import gnupg
import rich
import rich.pretty
Expand All @@ -20,7 +19,8 @@
rich.traceback.install()


def main( # pylint: disable=too-many-arguments
def main(
*,
dirpath: str,
recipient: str,
decryption_gpg_homedir: str = DECRYPTION_GPG_HOMEDIR,
Expand Down Expand Up @@ -50,13 +50,9 @@ def main( # pylint: disable=too-many-arguments
LOGGER.debug("Starting up")

# validation
dirpath = os.path.realpath(dirpath)
decryption_gpg_homedir = os.path.realpath(
os.path.expanduser(decryption_gpg_homedir)
)
encryption_gpg_homedir = os.path.realpath(
os.path.expanduser(encryption_gpg_homedir)
)
dirpath = str(Path(dirpath).absolute())
decryption_gpg_homedir = str(Path(decryption_gpg_homedir).expanduser().absolute())
encryption_gpg_homedir = str(Path(encryption_gpg_homedir).expanduser().absolute())

LOGGER.debug("dirpath=%s", dirpath)
LOGGER.debug("decryption_gpg_homedir=%s", decryption_gpg_homedir)
Expand All @@ -81,10 +77,11 @@ def main( # pylint: disable=too-many-arguments
extra={"markup": True},
)
else:
raise NameError(
msg = (
f"Secret key for recipient '{recipient}' not present in keyring at "
f"{encryption_gpg_homedir}"
f"{encryption_gpg_homedir}",
)
raise NameError(msg)

try:
updated_count = process_directory(
Expand Down
Loading

0 comments on commit 68b7030

Please sign in to comment.