Skip to content

Commit

Permalink
Add ruff linter to project
Browse files Browse the repository at this point in the history
  • Loading branch information
dzmpr committed Mar 29, 2024
1 parent e4b4f70 commit 9aeffdf
Show file tree
Hide file tree
Showing 21 changed files with 183 additions and 126 deletions.
21 changes: 20 additions & 1 deletion .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@ name: Run tests
on: [ push, pull_request ]

jobs:
ruff:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: 3.12

- name: Install ruff
run: |
python -m pip install --upgrade pip
pip install ruff==0.3.4
- name: Run ruff check
run: ruff check --output-format=github

run-tests:
strategy:
matrix:
Expand All @@ -15,7 +34,7 @@ jobs:
uses: actions/checkout@v4

- name: Setup Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: 3.11

Expand Down
34 changes: 34 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,37 @@ kataloger = "kataloger.__main__:main"

[tool.pytest.ini_options]
pythonpath = "src/"

[tool.ruff]
line-length = 120
indent-width = 4
target-version = "py38"
src = ["src", "tests"]

[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"ANN", # flake8-annotations
"COM", # flake8-commas
"C4", # flake8-comprehensions
"EM", # flake8-errmsg
"UP", # pyupgrade
"PYI", # flake8-pyi
"PT", # flake8-pytest-style
"RET", # flake8-return
"SIM", # flake8-simplify
"ARG", # flake8-unused-arguments
"PTH", # flake8-use-pathlib
]
ignore = [
"ANN101", # will be deprecated
"ANN102", # will be deprecated
"ANN204", # return type annotation for special methods
]

[tool.ruff.lint.per-file-ignores]
"tests/**/test_*.py" = ["ANN201", "ANN205"] # return not required for tests
3 changes: 1 addition & 2 deletions src/kataloger/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import sys

import asyncio
import sys

from kataloger.cli import cli
from kataloger.exceptions.kataloger_exception import KatalogerException
Expand Down
15 changes: 10 additions & 5 deletions src/kataloger/catalog_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ def __init__(
verbose: bool = False,
):
if not (library_repositories or plugin_repositories):
raise KatalogerConfigurationException("No repositories provided!")
message = "No repositories provided!"
raise KatalogerConfigurationException(message)

if not update_resolvers:
raise KatalogerConfigurationException("No update resolvers provided!")
message = "No update resolvers provided!"
raise KatalogerConfigurationException(message)

self.library_repositories = library_repositories
self.plugin_repositories = plugin_repositories
Expand Down Expand Up @@ -99,8 +101,11 @@ def try_find_update(
for resolver in self.update_resolvers:
(resolution, optional_update) = resolver.resolve(artifact, repositories_metadata)
match resolution:
case UpdateResolution.CANT_RESOLVE: continue
case UpdateResolution.UPDATE_FOUND: return optional_update
case UpdateResolution.NO_UPDATES: return None
case UpdateResolution.CANT_RESOLVE:
continue
case UpdateResolution.UPDATE_FOUND:
return optional_update
case UpdateResolution.NO_UPDATES:
return None

return None
3 changes: 1 addition & 2 deletions src/kataloger/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,4 @@ async def run() -> int:

if configuration.fail_on_updates and has_updates:
return 1
else:
return 0
return 0
17 changes: 8 additions & 9 deletions src/kataloger/cli/configuration_provider.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from argparse import ArgumentParser
from importlib.metadata import version
from importlib.resources import files, as_file
from importlib.resources import as_file, files
from pathlib import Path
from typing import Optional

Expand All @@ -14,7 +14,7 @@ def parse_configuration() -> KatalogerConfiguration:
prog="kataloger",
description="A Python command-line utility to discover updates for your gradle version catalogs.",
allow_abbrev=False,
epilog="Visit project repository to get more information."
epilog="Visit project repository to get more information.",
)
parser.add_argument(
"-p", "--path",
Expand Down Expand Up @@ -68,20 +68,20 @@ def parse_configuration() -> KatalogerConfiguration:
def _get_kataloger_version() -> str:
if __name__ == '__main__':
return "indev"
else:
return version(package_name)
return version(package_name)


def _get_catalog_paths(path_strings: list[str]) -> list[Path]:
if path_strings:
return list(map(lambda path: _str_to_path(path), path_strings))
return [_str_to_path(path) for path in path_strings]

# If catalog path not provided try to find catalogs in cwd.
catalog_files = Path.cwd().glob("*.versions.toml")
catalog_paths = list(filter(lambda path: path.exists() and path.is_file(), catalog_files))
if not catalog_paths:
raise KatalogerConfigurationException("Gradle version catalog not found in current directory. Please specify "
"path to catalog via parameter or run tool from directory with catalog.")
message = "Gradle version catalog not found in current directory. Please specify " \
"path to catalog via parameter or run tool from directory with catalog."
raise KatalogerConfigurationException(message)

return catalog_paths

Expand All @@ -95,8 +95,7 @@ def _get_repositories_path(path_string: Optional[str]) -> Path:
return repositories_candidate

with as_file(files(package_name).joinpath("default.repositories.toml")) as path:
bundled_repositories_path = path
return bundled_repositories_path
return path


def _str_to_path(path_string: str) -> Path:
Expand Down
2 changes: 1 addition & 1 deletion src/kataloger/cli/update_print_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def print_catalog_updates(
catalog_name: str,
catalog_count: int,
verbose: bool,
):
) -> None:
if catalog_name.endswith(".versions.toml"):
catalog_name = catalog_name.removesuffix(".versions.toml")
else:
Expand Down
2 changes: 1 addition & 1 deletion src/kataloger/helpers/log_helpers.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
def log_warning(message: str):
def log_warning(message: str) -> None:
print(f"W: {message}")
21 changes: 13 additions & 8 deletions src/kataloger/helpers/toml_parse_helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import tomllib
from pathlib import Path
from typing import Tuple

import tomllib
from yarl import URL

from kataloger.data.artifact.library import Library
Expand Down Expand Up @@ -100,7 +100,8 @@ def parse_libraries(catalog: dict[str, str | dict], versions: dict, verbose: boo
if verbose:
log_warning(f"Library \"{module}\" has no version in catalog.")
case _:
raise KatalogerParseException(f"Unknown library notation: {library}")
message = f"Unknown library notation: {library}"
raise KatalogerParseException(message)

return libraries

Expand Down Expand Up @@ -138,15 +139,17 @@ def parse_plugins(catalog: dict[str, str | dict], versions: dict, verbose: bool)
if verbose:
log_warning(f"Plugin \"{plugin_id}\" has no version in catalog.")
case _:
raise KatalogerParseException(f"Unknown plugin notation: {plugin}")
message = f"Unknown plugin notation: {plugin}"
raise KatalogerParseException(message)

return plugins


def __parse_declaration(declaration: str) -> Tuple[str, str]:
components = declaration.rsplit(':', 1)
if len(components) != 2 or not (components[0].strip() and components[1].strip()):
raise KatalogerParseException(f"Unknown declaration format: \"{declaration}\".")
message = f"Unknown declaration format: \"{declaration}\"."
raise KatalogerParseException(message)
return components[0], components[1]


Expand All @@ -156,14 +159,16 @@ def __get_version_by_reference(
artifact_name: str,
) -> str:
if not (version := versions.get(version_ref)):
raise KatalogerParseException(f"Version for \"{artifact_name}\" not specified by reference \"{version_ref}\".")
message = f"Version for \"{artifact_name}\" not specified by reference \"{version_ref}\"."
raise KatalogerParseException(message)

return version


def load_toml_to_dict(path: Path) -> dict[str, str | dict]:
with open(path, 'rb') as file:
with Path.open(path, "rb") as file:
try:
return tomllib.load(file)
except tomllib.TOMLDecodeError:
raise KatalogerParseException(f"Can't parse TOML in \"{path.name}\".")
except tomllib.TOMLDecodeError as parse_error:
message = f"Can't parse TOML in \"{path.name}\"."
raise KatalogerParseException(message) from parse_error
5 changes: 2 additions & 3 deletions src/kataloger/helpers/update_helpers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import asyncio
from collections import defaultdict
from typing import Optional

import asyncio
from aiohttp import BasicAuth
from aiohttp import ClientSession
from aiohttp import BasicAuth, ClientSession

from kataloger.data.artifact.artifact import Artifact
from kataloger.data.metadata_repository_info import MetadataRepositoryInfo
Expand Down
2 changes: 1 addition & 1 deletion src/kataloger/helpers/xml_parse_helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from pyexpat import ExpatError
from typing import Optional

import xmltodict
from pyexpat import ExpatError

from kataloger.data.artifact_metadata import ArtifactMetadata

Expand Down
2 changes: 1 addition & 1 deletion src/kataloger/update_resolver/base/update_resolver.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from abc import abstractmethod, ABC
from abc import ABC, abstractmethod
from typing import Optional

from kataloger.data.artifact.artifact import Artifact
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def __resolve_update_in_repository(

if artifact_version == update_version:
return UpdateResolution.NO_UPDATES, None
elif artifact_version < update_version:
if artifact_version < update_version:
update = ArtifactUpdate(
name=artifact.name,
update_repository_name=repository_metadata.repository.name,
Expand All @@ -81,8 +81,7 @@ def __resolve_update_in_repository(
def __most_recently_updated_repository(
repositories_metadata: list[MetadataRepositoryInfo],
) -> MetadataRepositoryInfo:
repository = max(repositories_metadata, key=lambda rm: rm.metadata.last_updated)
return repository
return max(repositories_metadata, key=lambda rm: rm.metadata.last_updated)

@staticmethod
def __repository_with_current_version(
Expand Down
14 changes: 8 additions & 6 deletions src/kataloger/update_resolver/universal/universal_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ def __init__(self, version: str):
def is_pre_release(self) -> bool:
return self.pre_release_name is not None

def __eq__(self, other) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, UniversalVersion):
return False

return self.raw == other.raw

def __lt__(self, other) -> bool:
def __lt__(self, other: object) -> bool:
if not isinstance(other, UniversalVersion):
return False

Expand All @@ -47,7 +47,7 @@ def to_digits_list(version_part: str) -> list[int]:
for self_digit, other_digit in zip_longest(self_digits, other_digits, fillvalue=0):
if self_digit < other_digit:
return True
elif self_digit > other_digit:
if self_digit > other_digit:
return False

# Numeric part is equal, lets compare pre-release part.
Expand All @@ -62,12 +62,14 @@ def to_digits_list(version_part: str) -> list[int]:
other_pr_index = other._pre_release_index()
if self_pr_index < other_pr_index:
return True
elif self_pr_index > other_pr_index:
if self_pr_index > other_pr_index:
return False
return False
elif not self.is_pre_release() and other.is_pre_release():

if not self.is_pre_release() and other.is_pre_release():
return False
elif self.is_pre_release() and not other.is_pre_release():

if self.is_pre_release() and not other.is_pre_release():
return True

return False
Expand Down
4 changes: 2 additions & 2 deletions src/kataloger/update_resolver/universal/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ def is_pre_release(self) -> bool:
raise NotImplementedError

@abstractmethod
def __eq__(self, other) -> bool:
def __eq__(self, other: object) -> bool:
raise NotImplementedError

@abstractmethod
def __lt__(self, other) -> bool:
def __lt__(self, other: object) -> bool:
raise NotImplementedError
4 changes: 2 additions & 2 deletions src/kataloger/update_resolver/universal/version_factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
from typing import Generic, TypeVar

from kataloger.update_resolver.universal.version import (Version)
from kataloger.update_resolver.universal.version import Version

T = TypeVar("T", bound=Version)

Expand Down
Loading

0 comments on commit 9aeffdf

Please sign in to comment.