mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-09 21:04:17 +00:00
file-contents-sorter should add newline at end of files missing newlines
Make an explicit 'else' path for readability
This commit is contained in:
parent
5dd1819e8b
commit
7102e0c8a3
2 changed files with 14 additions and 13 deletions
|
|
@ -18,14 +18,15 @@ FAIL = 1
|
||||||
|
|
||||||
|
|
||||||
def sort_file_contents(f):
|
def sort_file_contents(f):
|
||||||
before = [line.strip(b'\n\r') for line in f if line.strip()]
|
before = list(f)
|
||||||
after = sorted(before)
|
after = sorted([line.strip(b'\n\r') for line in before if line.strip()])
|
||||||
|
|
||||||
if before == after:
|
|
||||||
return PASS
|
|
||||||
|
|
||||||
|
before_string = b''.join(before)
|
||||||
after_string = b'\n'.join(after) + b'\n'
|
after_string = b'\n'.join(after) + b'\n'
|
||||||
|
|
||||||
|
if before_string == after_string:
|
||||||
|
return PASS
|
||||||
|
else:
|
||||||
f.seek(0)
|
f.seek(0)
|
||||||
f.write(after_string)
|
f.write(after_string)
|
||||||
f.truncate()
|
f.truncate()
|
||||||
|
|
|
||||||
|
|
@ -8,18 +8,18 @@ from pre_commit_hooks.file_contents_sorter import PASS
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
('input_s', 'expected_retval', 'output'),
|
('input_s', 'expected_retval', 'output'),
|
||||||
(
|
(
|
||||||
(b'', PASS, b''),
|
(b'', FAIL, b'\n'),
|
||||||
(b'lonesome\n', PASS, b'lonesome\n'),
|
(b'lonesome\n', PASS, b'lonesome\n'),
|
||||||
(b'missing_newline', PASS, b'missing_newline'),
|
(b'missing_newline', FAIL, b'missing_newline\n'),
|
||||||
(b'newline\nmissing', FAIL, b'missing\nnewline\n'),
|
(b'newline\nmissing', FAIL, b'missing\nnewline\n'),
|
||||||
(b'missing\nnewline', PASS, b'missing\nnewline'),
|
(b'missing\nnewline', FAIL, b'missing\nnewline\n'),
|
||||||
(b'alpha\nbeta\n', PASS, b'alpha\nbeta\n'),
|
(b'alpha\nbeta\n', PASS, b'alpha\nbeta\n'),
|
||||||
(b'beta\nalpha\n', FAIL, b'alpha\nbeta\n'),
|
(b'beta\nalpha\n', FAIL, b'alpha\nbeta\n'),
|
||||||
(b'C\nc\n', PASS, b'C\nc\n'),
|
(b'C\nc\n', PASS, b'C\nc\n'),
|
||||||
(b'c\nC\n', FAIL, b'C\nc\n'),
|
(b'c\nC\n', FAIL, b'C\nc\n'),
|
||||||
(b'mag ical \n tre vor\n', FAIL, b' tre vor\nmag ical \n'),
|
(b'mag ical \n tre vor\n', FAIL, b' tre vor\nmag ical \n'),
|
||||||
(b'@\n-\n_\n#\n', FAIL, b'#\n-\n@\n_\n'),
|
(b'@\n-\n_\n#\n', FAIL, b'#\n-\n@\n_\n'),
|
||||||
(b'extra\n\n\nwhitespace\n', PASS, b'extra\n\n\nwhitespace\n'),
|
(b'extra\n\n\nwhitespace\n', FAIL, b'extra\nwhitespace\n'),
|
||||||
(b'whitespace\n\n\nextra\n', FAIL, b'extra\nwhitespace\n'),
|
(b'whitespace\n\n\nextra\n', FAIL, b'extra\nwhitespace\n'),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue