Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions pre_commit_hooks/requirements_txt_fixer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,25 @@ def __lt__(self, requirement):

def fix_requirements(f):
requirements = []
before = []
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could even do tuple(f) (since tuples are smaller, faster, and best of all immutable!)

before = list(f)
after = []

for line in f:
before.append(line)
before_string = b''.join(before)

# If the file is empty (i.e. only whitespace/newlines) exit early
if before_string.strip() == b'':
return 0

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

requirement = requirements[-1]

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

before_string = b''.join(before)
after_string = b''.join(after)

if before_string == after_string:
Expand Down
2 changes: 2 additions & 0 deletions tests/requirements_txt_fixer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

# Input, expected return value, expected output
TESTS = (
(b'', 0, b''),
(b'\n', 0, b'\n'),
(b'foo\nbar\n', 1, b'bar\nfoo\n'),
(b'bar\nfoo\n', 0, b'bar\nfoo\n'),
(b'#comment1\nfoo\n#comment2\nbar\n', 1, b'#comment2\nbar\n#comment1\nfoo\n'),
Expand Down