Skip to content

Commit

Permalink
pyproject may not have project & dependencies keys
Browse files Browse the repository at this point in the history
  • Loading branch information
clavedeluna committed Nov 28, 2023
1 parent a64d219 commit b77acd6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
14 changes: 9 additions & 5 deletions src/codemodder/dependency_management/pyproject_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,20 @@ def add_to_file(
) -> Optional[ChangeSet]:
pyproject = self._parse_file()
original = deepcopy(pyproject)
pyproject["project"]["dependencies"].extend(
[f"{dep.requirement}" for dep in dependencies]
)

try:
pyproject["project"]["dependencies"].extend(
[f"{dep.requirement}" for dep in dependencies]
)
except tomlkit.exceptions.NonExistentKey:
return None

diff, added_line_nums = create_diff_and_linenums(
tomlkit.dumps(original).split("\n"), tomlkit.dumps(pyproject).split("\n")
)

if not dry_run:
with open(self.path, "w") as f:
with open(self.path, "w", encoding="utf-8") as f:
tomlkit.dump(pyproject, f)

changes = [
Expand All @@ -47,5 +51,5 @@ def add_to_file(
)

def _parse_file(self):
with open(self.path) as f:
with open(self.path, encoding="utf-8") as f:
return tomlkit.load(f)
32 changes: 29 additions & 3 deletions tests/dependency_management/test_pyproject_writer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from textwrap import dedent
import pytest

from packaging.requirements import Requirement
from codemodder.dependency_management.pyproject_writer import PyprojectWriter
from codemodder.dependency import DefusedXML, Security
from codemodder.project_analysis.file_parsers.package_store import PackageStore
Expand Down Expand Up @@ -125,7 +124,7 @@ def test_add_same_dependency_only_once(tmpdir):

writer = PyprojectWriter(store, tmpdir)
dependencies = [Security, Security]
changeset = writer.write(dependencies)
writer.write(dependencies)

updated_pyproject = """\
[build-system]
Expand Down Expand Up @@ -178,6 +177,33 @@ def test_dont_add_existing_dependency(tmpdir):

writer = PyprojectWriter(store, tmpdir)
dependencies = [Security]
changeset = writer.write(dependencies)
writer.write(dependencies)

assert pyproject_toml.read() == dedent(orig_pyproject)


def test_pyproject_no_dependencies(tmpdir):
orig_pyproject = """\
[build-system]
requires = ["setuptools", "setuptools_scm>=8"]
build-backend = "setuptools.build_meta"
[project]
name = "codemodder"
"""

pyproject_toml = tmpdir.join("pyproject.toml")
pyproject_toml.write(dedent(orig_pyproject))

store = PackageStore(
type="requirements.txt",
file=str(pyproject_toml),
dependencies=set(),
py_versions=[">=3.10.0"],
)

writer = PyprojectWriter(store, tmpdir)
dependencies = [Security]

writer.write(dependencies)

assert pyproject_toml.read() == dedent(orig_pyproject)

0 comments on commit b77acd6

Please sign in to comment.