Skip to content

fix: preserve comment indentation when rewriting requirements files - #1081

Open
citizen204 wants to merge 1 commit into
pypa:mainfrom
citizen204:fix-566-preserve-comment-indent
Open

fix: preserve comment indentation when rewriting requirements files#1081
citizen204 wants to merge 1 commit into
pypa:mainfrom
citizen204:fix-566-preserve-comment-indent

Conversation

@citizen204

Copy link
Copy Markdown

Summary

--fix strips the indentation of comment-only lines (e.g. the pip-compile-style # via ... backreference comment) when rewriting a requirements file, even though it correctly preserves everything else. The root cause is that pip-requirements-parser's comment parsing unconditionally .strip()s comment-only lines, discarding the leading whitespace that pip-compile uses to signal that a comment belongs to the preceding requirement rather than being a standalone comment.

Since that stripping happens inside the third-party parser before pip-audit ever sees the line, this fix recovers the original indentation from the source file at write time: for any parsed comment-only line, if the corresponding physical line in the original file is (once stripped) identical to the parsed comment, the original raw line (including its indentation) is written back instead of the parser's stripped version.

Changes

  • pip_audit/_dependency_source/requirement.py: in RequirementSource._fix_file, read the original file's lines once, and for each CommentRequirementLine restore the original line (with its indentation) when the physical line consists solely of that comment.
  • test/dependency_source/test_requirement.py: add test_requirement_source_fix_comments_preserve_indent covering the pip-compile-style indented # via ... comment from the issue, and update test_requirement_source_fix_explicit_subdep_comment_retention's expected output/docstring — this test previously codified the buggy unindented behavior as expected, and now asserts the corrected indentation instead.

Fixes #566

`pip-requirements-parser` unconditionally strips comment-only lines, which
discards the leading indentation `pip-compile` uses to mark a "# via ..."
backreference comment as belonging to the preceding requirement. When
`--fix` rewrote such a file, these comments lost their indentation. Recover
the original indentation from the source file when the physical line
consists solely of the comment.

Fixes pypa#566
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Preserve pip-tools comment indents

1 participant