Merge pull request #243 from pre-commit/comment_only_requirements_txt
Fix requirements-txt-fixer for comments at end of file
diff --git a/pre_commit_hooks/requirements_txt_fixer.py b/pre_commit_hooks/requirements_txt_fixer.py
index ffabf2a..1ee6fac 100644
--- a/pre_commit_hooks/requirements_txt_fixer.py
+++ b/pre_commit_hooks/requirements_txt_fixer.py
@@ -63,9 +63,16 @@
else:
requirement.value = line
+ # if a file ends in a comment, preserve it at the end
+ if requirements[-1].value is None:
+ rest = requirements.pop().comments
+ else:
+ rest = []
+
for requirement in sorted(requirements):
after.extend(requirement.comments)
after.append(requirement.value)
+ after.extend(rest)
after_string = b''.join(after)
diff --git a/tests/requirements_txt_fixer_test.py b/tests/requirements_txt_fixer_test.py
index dcf7a76..87e7b0c 100644
--- a/tests/requirements_txt_fixer_test.py
+++ b/tests/requirements_txt_fixer_test.py
@@ -11,6 +11,8 @@
(
(b'', PASS, b''),
(b'\n', PASS, b'\n'),
+ (b'# intentionally empty\n', PASS, b'# intentionally empty\n'),
+ (b'foo\n# comment at end\n', PASS, b'foo\n# comment at end\n'),
(b'foo\nbar\n', FAIL, b'bar\nfoo\n'),
(b'bar\nfoo\n', PASS, b'bar\nfoo\n'),
(b'#comment1\nfoo\n#comment2\nbar\n', FAIL, b'#comment2\nbar\n#comment1\nfoo\n'),