Skip to content

Commit e9446ff

Browse files
authored
Merge pull request #207 from dlgallagher/file_contents_sorter_hook_fix_bug_with_files_not_ending_in_newline
Fix bug with the file-contents-sorter hook when processing file that …
2 parents 50871f8 + 7102e0c commit e9446ff

File tree

3 files changed

+10
-6
lines changed

3 files changed

+10
-6
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ Add this to your `.pre-commit-config.yaml`
5151
with single quoted strings.
5252
- `end-of-file-fixer` - Makes sure files end in a newline and only a newline.
5353
- `fix-encoding-pragma` - Add `# -*- coding: utf-8 -*-` to the top of python files.
54-
- `file-contents-sorter` - Sort the lines in specified files (defaults to alphabetical). You must provide list of target files as input to it.
54+
- `file-contents-sorter` - Sort the lines in specified files (defaults to alphabetical). You must provide list of target files as input to it. Note that this hook WILL remove blank lines and does NOT respect any comments.
5555
- To remove the coding pragma pass `--remove` (useful in a python3-only codebase)
5656
- `flake8` - Run flake8 on your python files.
5757
- `forbid-new-submodules` - Prevent addition of new git submodules.

pre_commit_hooks/file_contents_sorter.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@
1818

1919

2020
def sort_file_contents(f):
21-
before = tuple(f)
22-
after = sorted(before)
21+
before = list(f)
22+
after = sorted([line.strip(b'\n\r') for line in before if line.strip()])
2323

2424
before_string = b''.join(before)
25-
after_string = b''.join(after)
25+
after_string = b'\n'.join(after) + b'\n'
2626

2727
if before_string == after_string:
2828
return PASS

tests/file_contents_sorter_test.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,19 @@
88
@pytest.mark.parametrize(
99
('input_s', 'expected_retval', 'output'),
1010
(
11-
(b'', PASS, b''),
11+
(b'', FAIL, b'\n'),
1212
(b'lonesome\n', PASS, b'lonesome\n'),
13-
(b'missing_newline', PASS, b'missing_newline'),
13+
(b'missing_newline', FAIL, b'missing_newline\n'),
14+
(b'newline\nmissing', FAIL, b'missing\nnewline\n'),
15+
(b'missing\nnewline', FAIL, b'missing\nnewline\n'),
1416
(b'alpha\nbeta\n', PASS, b'alpha\nbeta\n'),
1517
(b'beta\nalpha\n', FAIL, b'alpha\nbeta\n'),
1618
(b'C\nc\n', PASS, b'C\nc\n'),
1719
(b'c\nC\n', FAIL, b'C\nc\n'),
1820
(b'mag ical \n tre vor\n', FAIL, b' tre vor\nmag ical \n'),
1921
(b'@\n-\n_\n#\n', FAIL, b'#\n-\n@\n_\n'),
22+
(b'extra\n\n\nwhitespace\n', FAIL, b'extra\nwhitespace\n'),
23+
(b'whitespace\n\n\nextra\n', FAIL, b'extra\nwhitespace\n'),
2024
)
2125
)
2226
def test_integration(input_s, expected_retval, output, tmpdir):

0 commit comments

Comments
 (0)