From 7102e0c8a3db26c25a3795b098258c02c74649af Mon Sep 17 00:00:00 2001 From: Daniel Gallagher Date: Sun, 25 Jun 2017 19:51:50 -0700 Subject: [PATCH] file-contents-sorter should add newline at end of files missing newlines Make an explicit 'else' path for readability --- pre_commit_hooks/file_contents_sorter.py | 19 ++++++++++--------- tests/file_contents_sorter_test.py | 8 ++++---- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/pre_commit_hooks/file_contents_sorter.py b/pre_commit_hooks/file_contents_sorter.py index b66cc72..fe7f7ee 100644 --- a/pre_commit_hooks/file_contents_sorter.py +++ b/pre_commit_hooks/file_contents_sorter.py @@ -18,18 +18,19 @@ FAIL = 1 def sort_file_contents(f): - before = [line.strip(b'\n\r') for line in f if line.strip()] - after = sorted(before) - - if before == after: - return PASS + before = list(f) + after = sorted([line.strip(b'\n\r') for line in before if line.strip()]) + before_string = b''.join(before) after_string = b'\n'.join(after) + b'\n' - f.seek(0) - f.write(after_string) - f.truncate() - return FAIL + if before_string == after_string: + return PASS + else: + f.seek(0) + f.write(after_string) + f.truncate() + return FAIL def main(argv=None): diff --git a/tests/file_contents_sorter_test.py b/tests/file_contents_sorter_test.py index b635eb0..2c85c8a 100644 --- a/tests/file_contents_sorter_test.py +++ b/tests/file_contents_sorter_test.py @@ -8,18 +8,18 @@ from pre_commit_hooks.file_contents_sorter import PASS @pytest.mark.parametrize( ('input_s', 'expected_retval', 'output'), ( - (b'', PASS, b''), + (b'', FAIL, b'\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'missing\nnewline', PASS, b'missing\nnewline'), + (b'missing\nnewline', FAIL, b'missing\nnewline\n'), (b'alpha\nbeta\n', PASS, 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', FAIL, b'C\nc\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'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'), ) )