Skip to content

Commit

Permalink
move main linters to ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
mr-mixas committed Jun 21, 2024
1 parent 261dc6e commit f0d2860
Show file tree
Hide file tree
Showing 15 changed files with 89 additions and 75 deletions.
10 changes: 5 additions & 5 deletions nested_diff/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ class Differ:
def __init__(
self,
A=True, # noqa: N803
N=True,
O=True, # noqa: E741
R=True,
U=True,
trimR=False,
N=True, # noqa: N803
O=True, # noqa: E741 N803
R=True, # noqa: N803
U=True, # noqa: N803
trimR=False, # noqa: N803
dumper=None,
handlers=None,
):
Expand Down
6 changes: 3 additions & 3 deletions nested_diff/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def run(self):
Raises:
NotImplementedError: Must be implemented in derivatives.
""" # noqa: D406
"""
raise NotImplementedError


Expand All @@ -257,7 +257,7 @@ def __init__(self, header='', footer=''):
self.header = header
self.footer = footer

def encode(self, data): # noqa U100
def encode(self, data):
"""Encode data.
Args:
Expand Down Expand Up @@ -293,7 +293,7 @@ def dump(self, file_, data):
class Loader:
"""Base class for data loaders."""

def decode(self, data): # noqa U100
def decode(self, data):
"""Decode data.
Args:
Expand Down
15 changes: 7 additions & 8 deletions nested_diff/diff_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,10 @@ def generate_diffs(self):
if self.args.show:
if len(self.args.files) > 1:
headers_enabled = True
else:
if len(self.args.files) < 2:
self.argparser.error('Two or more arguments expected for diff')
elif len(self.args.files) > 2:
headers_enabled = True
elif len(self.args.files) < 2:
self.argparser.error('Two or more arguments expected for diff')
elif len(self.args.files) > 2:
headers_enabled = True

for file_ in self.args.files:
header = ''
Expand Down Expand Up @@ -308,7 +307,7 @@ def encode(self, data):
def get_formatter_class(self, base_class, values='repr'):
"""Return formatter class."""

class __Formatter(base_class):
class _Formatter(base_class):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

Expand All @@ -328,14 +327,14 @@ def __init__(self, *args, **kwargs):

self.generate_value = self.generate_multiline_value

def generate_empty_value(*args): # noqa U101
def generate_empty_value(*args): # noqa: ARG002
yield ''

def generate_multiline_value(self, value, tag, depth):
for line in self.__val_encoder.encode(value).splitlines():
yield from super().generate_string(line, tag, depth)

return __Formatter
return _Formatter

@staticmethod
def get_opts(opts):
Expand Down
2 changes: 1 addition & 1 deletion nested_diff/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def __init__(
for handler in handlers:
self.set_handler(handler)

def format(self, diff, **kwargs): # noqa A003
def format(self, diff, **kwargs):
"""Return formatted diff as string."""
return ''.join(self.generate_diff(diff, **kwargs))

Expand Down
16 changes: 8 additions & 8 deletions nested_diff/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def diff(self, differ, a, b):

return equal, diff

def patch(self, patcher, target, diff): # noqa U100
def patch(self, patcher, target, diff): # noqa: ARG002
"""Patch object.
Args:
Expand All @@ -82,7 +82,7 @@ def patch(self, patcher, target, diff): # noqa U100

raise ValueError(diff)

def iterate_diff(self, iterator, diff): # noqa U100
def iterate_diff(self, iterator, diff): # noqa: ARG002
"""Iterate over nested diff.
Args:
Expand Down Expand Up @@ -432,7 +432,7 @@ def patch(self, patcher, target, diff):

return target

def iterate_diff(self, iterator, diff): # noqa U100
def iterate_diff(self, iterator, diff): # noqa: ARG002
"""Iterate over nested diff.
Args:
Expand All @@ -443,7 +443,7 @@ def iterate_diff(self, iterator, diff): # noqa U100
Tuples with diff, key and subdiff for each nested diff.
"""
idx = 0 # noqa SIM113
idx = 0

for item in diff['D']:
try:
Expand All @@ -457,7 +457,7 @@ def iterate_diff(self, iterator, diff): # noqa U100

def generate_formatted_diff(self, formatter, diff, depth):
"""Generate formatted list diff."""
idx = 0 # noqa SIM113
idx = 0

for subdiff in diff['D']:
try:
Expand Down Expand Up @@ -583,7 +583,7 @@ def diff(self, differ, a, b):

return equal, {}

def patch(self, patcher, target, diff): # noqa U100
def patch(self, patcher, target, diff): # noqa: ARG002
"""Patch set object.
Args:
Expand Down Expand Up @@ -722,7 +722,7 @@ def diff(self, differ, a, b):

return equal, {'U': a} if differ.op_u else {}

def patch(self, patcher, target, diff): # noqa U100
def patch(self, patcher, target, diff): # noqa: ARG002
"""Patch text (multiline string).
Unlike GNU patch, this algorithm does not implement any heuristics and
Expand Down Expand Up @@ -775,7 +775,7 @@ def generate_formatted_diff(self, formatter, diff, depth):

if tag == 'I':
yield from formatter.generate_string(
'@@ -{} +{} @@'.format(
'@@ -{} +{} @@'.format( # noqa: UP032
self._get_hunk_range(value[0], value[1]),
self._get_hunk_range(value[2], value[3]),
),
Expand Down
62 changes: 42 additions & 20 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,12 @@ cli = [
]
lint = [
'darglint',
'flake8 < 5', # temp workaround (https://github.com/tholo/pytest-flake8/issues/87)
'flake8-builtins',
'flake8-bugbear',
'flake8-commas',
'flake8-comprehensions',
'flake8-docstrings',
'flake8-eradicate',
'flake8-pytest-style',
'flake8_quotes',
'flake8-return',
'flake8-unused-arguments',
'pep8-naming',
'pytest-flake8',
]
test = [
'pytest',
'pytest-cov',
'pytest-ruff',
'ruff==0.3.0', # pin for reproducible results
'ruff==0.4.10',
]

[project.scripts]
Expand Down Expand Up @@ -99,22 +86,57 @@ extend-exclude = [
]
line-length = 79

[tool.ruff.extend-per-file-ignores]
'tests/*' = [
'D', # docstrings
]

[tool.ruff.format]
docstring-code-format = true
quote-style = 'single'

[tool.ruff.lint]
select = [
'A',
'ARG',
'B',
'BLE',
'C4',
'COM',
'D',
'E501',
'DTZ',
'E',
'ERA',
'EXE',
# 'FBT', # TODO
'FLY',
'G',
'ICN',
'ISC',
'LOG',
'N',
'PGH',
'PIE',
'PT',
# 'PL', # TODO
'PLE',
'Q',
'RET',
'RSE',
'RUF',
'SIM',
'SLF',
'TD',
'UP',
'W',
]
ignore = [
'D407', # Missing dashed underline after section
'SIM105', # contextlib.suppress is slower than try-except-pass
]

[tool.ruff.lint.extend-per-file-ignores]
'tests/*' = [
'D', # docstrings
]

[tool.ruff.lint.flake8-quotes]
inline-quotes = 'single'

[tool.ruff.lint.pydocstyle]
convention = 'google'
12 changes: 6 additions & 6 deletions tests/cli/test_diff_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def test_default_diff_with_tty(capsys, expected, rpath):

def test_diff_method_kwargs_override(capsys, expected, rpath):
class TestApp(nested_diff.diff_tool.App):
def diff(self, a, b, **kwargs): # noqa U100
def diff(self, a, b, **kwargs): # noqa: ARG002
return super().diff(a, b, A=0, U=1)

exit_code = TestApp(
Expand All @@ -62,7 +62,7 @@ def diff(self, a, b, **kwargs): # noqa U100
assert captured.out == expected


def test_enable_U_ops(capsys, expected, rpath): # noqa N802
def test_enable_U_ops(capsys, expected, rpath): # noqa: N802
exit_code = nested_diff.diff_tool.App(
args=(
rpath('shared.lists.a.json'),
Expand All @@ -82,7 +82,7 @@ def test_enable_U_ops(capsys, expected, rpath): # noqa N802
assert captured.out == expected


def test_trimR_ops(capsys, expected, rpath): # noqa N802
def test_trimR_ops(capsys, expected, rpath): # noqa: N802
exit_code = nested_diff.diff_tool.App(
args=(
rpath('shared.lists.b.json'),
Expand Down Expand Up @@ -396,13 +396,13 @@ def test_yaml_ofmt(capsys, expected, rpath):
def test_python_yaml_impl(capsys, expected, rpath):
orig_import = builtins.__import__

def overridden_import(name, globals, locals, fromlist, level): # noqa A002
def overridden_import(name, globals, locals, fromlist, level): # noqa: A002
if name == 'yaml' and fromlist is not None:
for sym in ('CSafeDumper', 'CSafeLoader'):
if sym in fromlist:
raise ImportError(f'Mocked import error for yaml.{sym}')

return orig_import(name, globals, locals, fromlist, level) # noqa A002
return orig_import(name, globals, locals, fromlist, level)

with mock.patch('builtins.__import__', overridden_import):
exit_code = nested_diff.diff_tool.App(
Expand Down Expand Up @@ -482,7 +482,7 @@ def test_exit_code_diff_absent(rpath):
assert exit_code == 0


def test_exit_code_diff_absent_U_opt_enabled(rpath): # noqa N802
def test_exit_code_diff_absent_U_opt_enabled(rpath): # noqa: N802
exit_code = nested_diff.diff_tool.App(
args=(
rpath('shared.lists.a.json'),
Expand Down
2 changes: 1 addition & 1 deletion tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def iterate_test_suite(tests_map, results_mod, func):
try:
test['result'] = func(test)
results_map[name] = {'result': test['result']}
except Exception as e:
except Exception as e: # noqa: BLE001
results_map[name] = {
'raises': e if type(e) is type else type(e),
}
Expand Down
10 changes: 5 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
pytest.register_assert_rewrite('tests.common')


@pytest.fixture
@pytest.fixture()
def content():
def _reader(filename):
with open(filename) as f:
Expand All @@ -16,7 +16,7 @@ def _reader(filename):
return _reader


@pytest.fixture
@pytest.fixture()
def expected(request):
filename = os.path.splitext(request.module.__file__)[0]
filename += f'.{request.function.__name__}.exp'
Expand All @@ -25,7 +25,7 @@ def expected(request):
return f.read()


@pytest.fixture
@pytest.fixture()
def rpath(request):
def _path_resolver(filename):
path = os.path.join(
Expand All @@ -41,7 +41,7 @@ def _path_resolver(filename):
return _path_resolver


@pytest.fixture
@pytest.fixture()
def stringio():
return StringIO()

Expand All @@ -51,6 +51,6 @@ def isatty(self):
return True


@pytest.fixture
@pytest.fixture()
def stringio_tty():
return _StringIOTTY()
8 changes: 4 additions & 4 deletions tests/data/gen_html_compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ def main():

try:
txt = TextFormatter(**fmt_obj_opts).format(diff)
except Exception as e:
txt = f'<div class="error">ERROR: {str(e)}</div>'
except Exception as e: # noqa: BLE001
txt = f'<div class="error">ERROR: {e}</div>'
else:
txt = f'<pre>{html.escape(txt)}</pre>'

try:
htm = HtmlFormatter(**fmt_obj_opts).format(diff)
except Exception as e:
htm = f'<div class="error">ERROR: {str(e)}</div>'
except Exception as e: # noqa: BLE001
htm = f'<div class="error">ERROR: {e}</div>'

print(f'<tr><td colspan=2 class="label">{name}</td></tr>')
print(f'<tr><td>{txt}</td>')
Expand Down
2 changes: 1 addition & 1 deletion tests/data/gen_standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def generate_tests(source_dir=sys.argv[1]):
test_opts['trimR'] = True

if 'patched' in data:
patched = f"\n 'patched': {repr(data['patched'])},"
patched = f"\n 'patched': {data['patched']!r},"
else:
patched = ''

Expand Down
Loading

0 comments on commit f0d2860

Please sign in to comment.