Fix bug with the file-contents-sorter hook when processing file that does not end in a newline
diff --git a/pre_commit_hooks/file_contents_sorter.py b/pre_commit_hooks/file_contents_sorter.py index 6fa3bc0..b66cc72 100644 --- a/pre_commit_hooks/file_contents_sorter.py +++ b/pre_commit_hooks/file_contents_sorter.py
@@ -18,19 +18,18 @@ def sort_file_contents(f): - before = tuple(f) + before = [line.strip(b'\n\r') for line in f if line.strip()] after = sorted(before) - before_string = b''.join(before) - after_string = b''.join(after) - - if before_string == after_string: + if before == after: return PASS - else: - f.seek(0) - f.write(after_string) - f.truncate() - return FAIL + + after_string = b'\n'.join(after) + b'\n' + + 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 5f4dc5b..b635eb0 100644 --- a/tests/file_contents_sorter_test.py +++ b/tests/file_contents_sorter_test.py
@@ -11,12 +11,16 @@ (b'', PASS, b''), (b'lonesome\n', PASS, b'lonesome\n'), (b'missing_newline', PASS, b'missing_newline'), + (b'newline\nmissing', FAIL, b'missing\nnewline\n'), + (b'missing\nnewline', PASS, b'missing\nnewline'), (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'whitespace\n\n\nextra\n', FAIL, b'extra\nwhitespace\n'), ) ) def test_integration(input_s, expected_retval, output, tmpdir):