Skip to content

Commit 2d1d4e3

Browse files
authored
Requirements parser handles trailing comments (#315)
requirements parser handles trailing comments
1 parent 7075794 commit 2d1d4e3

3 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/codemodder/project_analysis/file_parsers/requirements_txt_file_parser.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def _parse_file(self, file: Path) -> PackageStore | None:
2828
logger.debug("Unknown encoding for file: %s", file)
2929
return None
3030

31-
dependencies = set(line.strip() for line in lines if not line.startswith("#"))
31+
dependencies = set(
32+
line.split("#")[0].strip() for line in lines if not line.startswith("#")
33+
)
3234

3335
return PackageStore(
3436
type=self.file_type,

tests/conftest.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,15 @@ def pkg_with_reqs_txt(tmp_path_factory):
4444
return base_dir
4545

4646

47+
@pytest.fixture(scope="module")
48+
def pkg_with_reqs_txt_and_comments(tmp_path_factory):
49+
base_dir = tmp_path_factory.mktemp("foo")
50+
req_file = base_dir / "requirements.txt"
51+
reqs = "# comment\nrequests==2.31.0\nblack==23.7.*\nmypy~=1.4 # comment\npylint>1\n"
52+
req_file.write_text(reqs)
53+
return base_dir
54+
55+
4756
@pytest.fixture(scope="module")
4857
def pkg_with_reqs_txt_utf_16(tmp_path_factory):
4958
base_dir = tmp_path_factory.mktemp("foo")

tests/project_analysis/file_parsers/test_requirements_txt_file_parser.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,13 @@ def test_open_error(self, pkg_with_reqs_txt, mocker):
3737
parser = RequirementsTxtParser(pkg_with_reqs_txt)
3838
found = parser.parse()
3939
assert len(found) == 0
40+
41+
def test_trailing_comments(self, pkg_with_reqs_txt_and_comments):
42+
parser = RequirementsTxtParser(pkg_with_reqs_txt_and_comments)
43+
found = parser.parse()
44+
assert len(found) == 1
45+
store = found[0]
46+
assert store.type.value == "requirements.txt"
47+
assert store.file == pkg_with_reqs_txt_and_comments / parser.file_type.value
48+
assert store.py_versions == []
49+
assert len(store.dependencies) == 4

0 commit comments

Comments
 (0)