Skip to content

Commit

Permalink
Don't lint binary files (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
KyleFromNVIDIA authored Jan 22, 2024
1 parent 5ff1143 commit 67defbc
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 6 deletions.
20 changes: 16 additions & 4 deletions src/rapids_pre_commit_hooks/lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@
import contextlib
import functools
import itertools
import warnings


class OverlappingReplacementsError(RuntimeError):
pass


class BinaryFileWarning(Warning):
pass


class Replacement:
def __init__(self, pos, newtext):
self.pos = pos
Expand Down Expand Up @@ -206,11 +211,18 @@ def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
return

warnings = False
has_warnings = False

for file in self.args.files:
with open(file) as f:
content = f.read()
try:
content = f.read()
except UnicodeDecodeError:
warnings.warn(
f"Refusing to run text linter on binary file {file}.",
BinaryFileWarning,
)
continue

linter = Linter(file, content)
for check in self.checks:
Expand All @@ -224,9 +236,9 @@ def __exit__(self, exc_type, exc_value, traceback):
f.write(fix)

if len(linter.warnings) > 0:
warnings = True
has_warnings = True

if warnings:
if has_warnings:
exit(1)


Expand Down
37 changes: 35 additions & 2 deletions test/rapids_pre_commit_hooks/test_lint.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@
# limitations under the License.

import tempfile
from unittest.mock import patch
from unittest.mock import Mock, patch

import pytest

from rapids_pre_commit_hooks.lint import Linter, LintMain, OverlappingReplacementsError
from rapids_pre_commit_hooks.lint import (
BinaryFileWarning,
Linter,
LintMain,
OverlappingReplacementsError,
)


class TestLinter:
Expand Down Expand Up @@ -129,6 +134,14 @@ def hello_file(self):
f.seek(0)
yield f

@pytest.fixture
def binary_file(self):
with tempfile.NamedTemporaryFile("wb+") as f:
f.write(b"\xDE\xAD\xBE\xEF")
f.flush()
f.seek(0)
yield f

def the_check(self, linter, args):
assert args.check_test
linter.add_warning((0, 5), "say good bye instead").add_replacement(
Expand Down Expand Up @@ -281,3 +294,23 @@ def test_multiple_files(self, hello_world_file, hello_file, capsys):
"""
)

def test_binary_file(self, binary_file, capsys):
mock_linter = Mock(wraps=Linter)
with patch(
"sys.argv",
[
"check-test",
"--check-test",
"--fix",
binary_file.name,
],
), patch("rapids_pre_commit_hooks.lint.Linter", mock_linter), pytest.warns(
BinaryFileWarning,
match=r"^Refusing to run text linter on binary file .*\.$",
):
m = LintMain()
m.argparser.add_argument("--check-test", action="store_true")
with m.execute() as ctx:
ctx.add_check(self.the_check)
mock_linter.assert_not_called()

0 comments on commit 67defbc

Please sign in to comment.