Skip to content

Commit

Permalink
rollback poetry.lock when a failure to add detected
Browse files Browse the repository at this point in the history
  • Loading branch information
wagnerluis1982 committed Feb 12, 2023
1 parent 3e67146 commit dd7be3b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/poetry/console/commands/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def handle(self) -> int:

# Refresh the locker
self.poetry.set_locker(
self.poetry.locker.__class__(self.poetry.locker.lock, poetry_content)
self.poetry.locker.copy_with(self.poetry.locker.lock, poetry_content)
)
self.installer.set_locker(self.poetry.locker)

Expand All @@ -261,9 +261,29 @@ def handle(self) -> int:

status = self.installer.run()

if status == 0 and not self.option("dry-run"):
if self.option("dry-run"):
return status

if status == 0:
assert isinstance(content, TOMLDocument)
self.poetry.file.write(content)
else:
# rollback poetry.lock
for r in requirements:
section.remove(r["name"])
with contextlib.suppress(ValueError):
self.poetry.package.dependency_group(group).remove_dependency(
r["name"]
)

self.poetry.set_locker(
self.poetry.locker.copy_with(self.poetry.locker.lock, poetry_content)
)
self.installer.set_locker(self.poetry.locker)

self.installer.lock(update=True)
self.installer.whitelist([])
self.installer.run()

return status

Expand Down
3 changes: 3 additions & 0 deletions src/poetry/packages/locker.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,9 @@ def set_lock_data(self, root: Package, packages: list[Package]) -> bool:
self._write_lock_data(lock)
return do_write

def copy_with(self, lock: str | Path, local_config: dict[str, Any]) -> Locker:
return self.__class__(lock, local_config)

def _write_lock_data(self, data: TOMLDocument) -> None:
lockfile = TOMLFile(self.lock)
lockfile.write(data)
Expand Down
12 changes: 12 additions & 0 deletions tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,12 @@ def __init__(self, lock: str | Path, local_config: dict) -> None:
self._lock_data = None
self._write = False

@property
def lock(self) -> Path:
if isinstance(self._lock, TOMLFile):
return self._lock.path
return self._lock

def write(self, write: bool = True) -> None:
self._write = write

Expand All @@ -215,6 +221,12 @@ def mock_lock_data(self, data: dict) -> None:
def is_fresh(self) -> bool:
return True

def copy_with(self, lock: str | Path, local_config: dict[str, Any]) -> TestLocker:
new_locker = TestLocker(lock, local_config)
new_locker._locked = self._locked
new_locker._write = self._write
return new_locker

def _write_lock_data(self, data: TOMLDocument) -> None:
if self._write:
super()._write_lock_data(data)
Expand Down

0 comments on commit dd7be3b

Please sign in to comment.