Skip to content

Commit 4fe8894

Browse files
authored
Handle requirements.txt file with -r line (#416)
be able to handle requirements.txt file with -r line
1 parent 53ed01f commit 4fe8894

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

src/codemodder/project_analysis/file_parsers/requirements_txt_file_parser.py

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

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

3634
return PackageStore(
3735
type=self.file_type,
@@ -42,3 +40,13 @@ def _parse_file(self, file: Path) -> PackageStore | None:
4240
# and extracting py versions from them.
4341
py_versions=[],
4442
)
43+
44+
def _clean_lines(self, lines: list[str]) -> set[str]:
45+
"""Return a set of dependency `lines` excluding any lines
46+
that may be comments or may be pointers to other requirement files (-r ..._
47+
"""
48+
return set(
49+
line.split("#")[0].strip()
50+
for line in lines
51+
if not (line.startswith("#") or line.startswith("-r "))
52+
)

tests/conftest.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ def pkg_with_reqs_txt(tmp_path_factory):
4545
return base_dir
4646

4747

48+
@pytest.fixture(scope="module")
49+
def pkg_with_reqs_r_line(tmp_path_factory):
50+
base_dir = tmp_path_factory.mktemp("foo")
51+
req_file = base_dir / "requirements.txt"
52+
second_req_file = base_dir / "more_requirements.txt"
53+
second_req_file.write_text("django<5")
54+
reqs = "# comment\nrequests==2.31.0\nblack==23.7.*\nmypy~=1.4\npylint>1\n-r more_requirements.txt\n"
55+
req_file.write_text(reqs)
56+
return base_dir
57+
58+
4859
@pytest.fixture(scope="module")
4960
def pkg_with_reqs_txt_and_comments(tmp_path_factory):
5061
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
@@ -47,3 +47,13 @@ def test_trailing_comments(self, pkg_with_reqs_txt_and_comments):
4747
assert store.file == pkg_with_reqs_txt_and_comments / parser.file_type.value
4848
assert store.py_versions == []
4949
assert len(store.dependencies) == 4
50+
51+
def test_parse_with_r_line(self, pkg_with_reqs_r_line):
52+
parser = RequirementsTxtParser(pkg_with_reqs_r_line)
53+
found = parser.parse()
54+
assert len(found) == 1
55+
store = found[0]
56+
assert store.type.value == "requirements.txt"
57+
assert store.file == pkg_with_reqs_r_line / parser.file_type.value
58+
assert store.py_versions == []
59+
assert len(store.dependencies) == 4

0 commit comments

Comments
 (0)