diff --git a/src/codemodder/dependency_management/pyproject_writer.py b/src/codemodder/dependency_management/pyproject_writer.py index 6f6c4346..e869fe28 100644 --- a/src/codemodder/dependency_management/pyproject_writer.py +++ b/src/codemodder/dependency_management/pyproject_writer.py @@ -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 = [ @@ -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) diff --git a/tests/dependency_management/test_pyproject_writer.py b/tests/dependency_management/test_pyproject_writer.py index 1a60d495..fa8fe5b3 100644 --- a/tests/dependency_management/test_pyproject_writer.py +++ b/tests/dependency_management/test_pyproject_writer.py @@ -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 @@ -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] @@ -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)