Skip to content

Commit

Permalink
Ruff, mypy lint (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
blablatdinov authored May 16, 2024
1 parent fa4d36b commit 6f639a1
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 40 deletions.
86 changes: 86 additions & 0 deletions .github/workflows/pr-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# The MIT License (MIT).
#
# Copyright (c) 2024 Almaz Ilaletdinov <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.

name: Check pull request

on:
pull_request:
branches: [ "master" ]

permissions:
contents: read

jobs:
tests:
strategy:
matrix:
python_version: ["3.9", "3.12"]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python_version }}
- name: Install Poetry
uses: snok/[email protected]
with:
virtualenvs-create: true
virtualenvs-in-project: true
installer-parallel: true
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v4
with:
path: .venv
key: venv-${{ matrix.python_version }}-${{ hashFiles('**/poetry.lock') }}
- name: Install dependencies
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
run: poetry install --no-interaction
- name: Run tests via pytest
run: make test

lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12.1"
- name: Install Poetry
uses: snok/[email protected]
with:
virtualenvs-create: true
virtualenvs-in-project: true
installer-parallel: true
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v4
with:
path: .venv
key: venv-3.12-${{ hashFiles('**/poetry.lock') }}
- name: Install dependencies
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
run: poetry install --no-interaction
- name: Lint
run: make lint
9 changes: 5 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
# OR OTHER DEALINGS IN THE SOFTWARE.

lint:
poetry run isort deltaver tests
poetry run ruff check deltaver tests --fix
poetry run mypy deltaver tests
poetry run isort ondivi tests
poetry run ruff check ondivi tests --fix
# poetry run flake8 ondivi tests
poetry run mypy ondivi tests --strict

test:
poetry run pytest --cov=ondivi --cov-report=term-missing:skip-covered
poetry run pytest --cov=ondivi --cov-report=term-missing:skip-covered -vv
37 changes: 18 additions & 19 deletions ondivi/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,39 +24,38 @@

from git import Repo

Diff = str
FileName = str

def define_changed_lines(diff):

def define_changed_lines(diff: Diff) -> dict[FileName, list[int]]:
"""Поиск измененных строк в файлах.
:return: dict
:param diff: Diff
:return: dict[FileName, list[int]]
"""
res = {}
current_file = None
res: dict[FileName, list[int]] = {}
current_file = ''
for line in diff.splitlines():
if line.startswith('diff --git'):
current_file = line.split(' b/')[-1].strip()
res[current_file] = []
elif line.startswith('@@'):
line = line.split('@@')[1].strip()
added_lines = line.split('+')[1]
splitted_line = line.split('@@')[1].strip()
added_lines = splitted_line.split('+')[1]
start_line = int(
added_lines.split(',')[0],
)
if ',' not in added_lines:
num_lines = 0
else:
num_lines = int(
added_lines.split(',')[1],
) - 1
num_lines = 0 if ',' not in added_lines else int(added_lines.split(',')[1]) - 1
res[current_file].extend(list(range(
start_line, start_line + num_lines + 1,
)))
return res


def filter_out_violations(changed_lines, violations: list[str]):
def filter_out_violations(changed_lines: dict[FileName, list[int]], violations: list[str]) -> list[str]:
res = []
for violation in violations.splitlines():
for violation in violations:
with suppress(ValueError, IndexError):
filename = violation.split(':')[0]
line = int(violation.split(':')[1])
Expand All @@ -68,24 +67,24 @@ def filter_out_violations(changed_lines, violations: list[str]):
return res


def controller(diff, violations):
def controller(diff: Diff, violations: list[str]) -> list[str]:
changed_lines = define_changed_lines(diff)
return filter_out_violations(changed_lines, violations)


def main():
def main() -> None:
a = 'not empty'
violations = []
while a:
try:
a = input()
violations.append(a)
except EOFError:
except EOFError: # noqa: PERF203
break
print('\n'.join(
print('\n'.join( # noqa: T201
controller(
Repo('.').git.diff('--unified=0', 'origin/master..HEAD'),
'\n'.join(violations),
violations,
),
))

Expand Down
60 changes: 59 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 10 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ readme = "README.md"

[tool.poetry.dependencies]
python = ">=3.9,<3.13"
gitpython = "3.1.43"
gitpython = "^3.0"

[tool.poetry.scripts]
ondivi = "ondivi.__main__:main"
Expand All @@ -17,20 +17,19 @@ ruff = "0.4.4"
wemake-python-styleguide = "0.19.2"
pytest = "8.2.0"
isort = "5.13.2"
pytest-cov = "^5.0.0"
pytest-cov = "5.0.0"
mypy = "1.10.0"

[tool.isort]
line_length = 120
multi_line_output = 3
include_trailing_comma = true

[tool.ruff]
[tool.ruff.lint]
select = ["ALL"]
fixable = [
"F401", # Unused import
]
line-length = 120
target-version = "py39"
ignore = [
"D", # TODO: write docstrings
"ANN101", # Missing type annotation for `self` in method
Expand Down Expand Up @@ -58,12 +57,16 @@ ignore = [
"TCH003", # Move standard library import `...` into a type-checking block
]

[tool.ruff.flake8-quotes]
[tool.ruff]
line-length = 120
target-version = "py39"

[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "single"
multiline-quotes = "double"

[tool.ruff.per-file-ignores]
[tool.ruff.lint.per-file-ignores]
"tests/*" = [
"S101", # use of `assert` detected
"PLR2004", # Magic value
Expand Down
29 changes: 20 additions & 9 deletions tests/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.

import subprocess
from pathlib import Path

from ondivi.__main__ import define_changed_lines, controller
from ondivi.__main__ import controller, define_changed_lines


def test_define_changed_files():
def test_define_changed_files() -> None:
got = define_changed_lines(
Path('tests/fixtures/diff.txt').read_text(),
)
Expand All @@ -48,21 +47,33 @@ def test_define_changed_files():
}


def test_controller():
def test_controller() -> None:
got = controller(
Path('tests/fixtures/diff.txt').read_text(),
Path('tests/fixtures/violations.txt').read_text(),
Path('tests/fixtures/violations.txt').read_text().splitlines(),
)

assert got == [
'src/app_types/listable.py:23:1: UP035 Import from `collections.abc` instead: `Sequence`',
'src/srv/ayats/ayats_by_text_query.py:23:1: UP035 Import from `collections.abc` instead: `Sequence`',
'src/srv/ayats/ayats_by_text_query.py:23:47: F401 [*] `typing.Generic` imported but unused',
'src/srv/ayats/favorite_ayats_after_remove.py:23:1: UP035 Import from `collections.abc` instead: `Sequence`',
'src/srv/ayats/pg_ayat.py:64:30: PLR2004 Magic value used in comparison, consider replacing `4096` with a constant variable',
' '.join([
'src/srv/ayats/pg_ayat.py:64:30: PLR2004 Magic value used in comparison,',
'consider replacing `4096` with a constant variable',
]),
'src/srv/ayats/pg_ayat.py:66:44: COM812 Trailing comma missing',
"src/tests/it/srv/ayats/test_pg_ayat.py:78:19: PLC1901 `got == ''` can be simplified to `not got` as an empty string is falsey",
' '.join([
"src/tests/it/srv/ayats/test_pg_ayat.py:78:19: PLC1901 `got == ''` can be simplified",
'to `not got` as an empty string is falsey',
]),
'src/app_types/listable.py:33:20: PYI059 `Generic[]` should always be the last base class',
'src/tests/it/srv/ayats/test_pg_ayat.py:90:13: PLW1514 `pathlib.Path(...).read_text` without explicit `encoding` argument',
'src/tests/it/srv/ayats/test_pg_ayat.py:95:19: PLW1514 `pathlib.Path(...).read_text` without explicit `encoding` argument',
' '.join([
'src/tests/it/srv/ayats/test_pg_ayat.py:90:13: PLW1514 `pathlib.Path(...).read_text`',
'without explicit `encoding` argument',
]),
' '.join([
'src/tests/it/srv/ayats/test_pg_ayat.py:95:19: PLW1514 `pathlib.Path(...).read_text`',
'without explicit `encoding` argument',
]),
]

0 comments on commit 6f639a1

Please sign in to comment.