Skip to content

Commit 7ccfa05

Browse files
author
Daniel Gallagher
committed
Fix NoneTypeError when requirements file is empty
1 parent 78818b9 commit 7ccfa05

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

pre_commit_hooks/requirements_txt_fixer.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,21 +30,25 @@ def __lt__(self, requirement):
3030

3131
def fix_requirements(f):
3232
requirements = []
33-
before = []
33+
before = list(f)
3434
after = []
3535

36-
for line in f:
37-
before.append(line)
36+
before_string = b''.join(before)
37+
38+
# If the file is empty (i.e. only whitespace/newlines) exit early
39+
if before_string.strip() == b'':
40+
return 0
3841

39-
# If the most recent requirement object has a value, then it's time to
40-
# start building the next requirement object.
42+
for line in before:
43+
# If the most recent requirement object has a value, then it's
44+
# time to start building the next requirement object.
4145
if not len(requirements) or requirements[-1].value is not None:
4246
requirements.append(Requirement())
4347

4448
requirement = requirements[-1]
4549

46-
# If we see a newline before any requirements, then this is a top of
47-
# file comment.
50+
# If we see a newline before any requirements, then this is a
51+
# top of file comment.
4852
if len(requirements) == 1 and line.strip() == b'':
4953
if len(requirement.comments) and requirement.comments[0].startswith(b'#'):
5054
requirement.value = b'\n'
@@ -60,7 +64,6 @@ def fix_requirements(f):
6064
after.append(comment)
6165
after.append(requirement.value)
6266

63-
before_string = b''.join(before)
6467
after_string = b''.join(after)
6568

6669
if before_string == after_string:

tests/requirements_txt_fixer_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
# Input, expected return value, expected output
77
TESTS = (
8+
(b'', 0, b''),
9+
(b'\n', 0, b'\n'),
810
(b'foo\nbar\n', 1, b'bar\nfoo\n'),
911
(b'bar\nfoo\n', 0, b'bar\nfoo\n'),
1012
(b'#comment1\nfoo\n#comment2\nbar\n', 1, b'#comment2\nbar\n#comment1\nfoo\n'),

0 commit comments

Comments
 (0)