Skip to content

Commit da2ea3f

Browse files
committed
add new line post reading requirements file, change before from tuple to list, add test cases
1 parent 277f875 commit da2ea3f

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

pre_commit_hooks/requirements_txt_fixer.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,14 @@ def __lt__(self, requirement): # type: (Requirement) -> int
4040

4141
def fix_requirements(f): # type: (IO[bytes]) -> int
4242
requirements = [] # type: List[Requirement]
43-
before = tuple(f)
43+
before = list(f) # type: List[bytes]
4444
after = [] # type: List[bytes]
4545

46+
# adds new line in case one is missing
47+
# AND a change to the requirements file is needed regardless:
48+
if before and not before[-1].endswith(b'\n'):
49+
before[-1] += b'\n'
50+
4651
before_string = b''.join(before)
4752

4853
# If the file is empty (i.e. only whitespace/newlines) exit early
@@ -94,7 +99,7 @@ def fix_requirements(f): # type: (IO[bytes]) -> int
9499

95100
after_string = b''.join(after)
96101

97-
if before_string == after_string:
102+
if before_string.rstrip() == after_string.rstrip():
98103
return PASS
99104
else:
100105
f.seek(0)

tests/requirements_txt_fixer_test.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
(b'foo\n# comment at end\n', PASS, b'foo\n# comment at end\n'),
1616
(b'foo\nbar\n', FAIL, b'bar\nfoo\n'),
1717
(b'bar\nfoo\n', PASS, b'bar\nfoo\n'),
18+
(b'a\nc\nb\n', FAIL, b'a\nb\nc\n'),
19+
(b'a\nc\nb', FAIL, b'a\nb\nc\n'),
20+
(b'a\nb\nc', PASS, b'a\nb\nc'),
1821
(
1922
b'#comment1\nfoo\n#comment2\nbar\n',
2023
FAIL,

0 commit comments

Comments
 (0)