diff --git a/src/poetry/packages/locker.py b/src/poetry/packages/locker.py index 2031194d492..822e0a59be5 100644 --- a/src/poetry/packages/locker.py +++ b/src/poetry/packages/locker.py @@ -323,6 +323,14 @@ def _get_lock_data(self) -> dict[str, Any]: except tomllib.TOMLDecodeError as e: raise RuntimeError(f"Unable to read the lock file ({e}).") + # if the lockfile doesn't contain a metadata section at all, + # it probably needs to be rebuilt completely + if "metadata" not in lock_data: + raise RuntimeError( + "The lock file does not have a metadata entry.\n" + "Regenerate the lock file with the `poetry lock` command." + ) + metadata = lock_data["metadata"] lock_version = Version.parse(metadata.get("lock-version", "1.0")) current_version = Version.parse(self._VERSION) diff --git a/tests/packages/test_locker.py b/tests/packages/test_locker.py index 715ba5efb33..e115c32c799 100644 --- a/tests/packages/test_locker.py +++ b/tests/packages/test_locker.py @@ -622,6 +622,38 @@ def test_reading_lock_file_should_raise_an_error_on_invalid_data( assert "Unable to read the lock file" in str(e.value) +def test_reading_lock_file_should_raise_an_error_on_missing_metadata( + locker: Locker, +) -> None: + content = f"""\ +# {GENERATED_COMMENT} + +[[package]] +name = "A" +version = "1.0.0" +description = "" +optional = false +python-versions = "*" +files = [] + +[package.source] +type = "legacy" +url = "https://foo.bar" +reference = "legacy" +""" + with locker.lock.open("w", encoding="utf-8") as f: + f.write(content) + + with pytest.raises(RuntimeError) as e: + _ = locker.lock_data + + assert ( + "The lock file does not have a metadata entry.\nRegenerate the lock file with" + " the `poetry lock` command." + in str(e.value) + ) + + def test_locking_legacy_repository_package_should_include_source_section( root: ProjectPackage, locker: Locker ) -> None: