clan-cli: do not crash if a machine being deleted is missing from the inventory

We implement that by actually raising `KeyError` in `inventory.delete_by_path`
(as advertised in the docstring), since it makes more sense to catch a
`KeyError` than a generic `ClanError`.
This commit is contained in:
Louis Opter
2025-03-10 22:06:06 +00:00
committed by Mic92
parent 538374558d
commit 039b309255
3 changed files with 20 additions and 11 deletions

View File

@@ -431,7 +431,7 @@ def delete_by_path(d: dict[str, Any], path: str) -> Any:
"""
if not path:
msg = "Cannot delete. Path is empty."
raise ClanError(msg)
raise KeyError(msg)
keys = path.split(".")
current = d
@@ -439,17 +439,17 @@ def delete_by_path(d: dict[str, Any], path: str) -> Any:
# Navigate to the parent dictionary of the final key
for key in keys[:-1]:
if key not in current or not isinstance(current[key], dict):
msg = f"Cannot delete. Key '{path}' not found or not a dictionary '{d}'."
raise ClanError(msg)
msg = f"Cannot delete. Key '{path}' not found or not a dictionary '{d}'"
raise KeyError(msg)
current = current[key]
# Attempt to pop the final key
last_key = keys[-1]
try:
value = current.pop(last_key)
except KeyError:
msg = f"Cannot delete. Path '{path}' not found in data '{d}'. "
raise ClanError(msg) from KeyError
except KeyError as exc:
msg = f"Cannot delete. Path '{path}' not found in data '{d}'"
raise KeyError(msg) from exc
else:
return {last_key: value}

View File

@@ -28,7 +28,16 @@ log = logging.getLogger(__name__)
@API.register
def delete_machine(flake: Flake, name: str) -> None:
inventory.delete(str(flake.path), {f"machines.{name}"})
try:
inventory.delete(str(flake.path), {f"machines.{name}"})
except KeyError as exc:
# louis@(2025-03-09): test infrastructure does not seem to set the
# inventory properly, but more importantly only one machine in my
# personal clan ended up in the inventory for some reason, so I think
# it makes sense to eat the exception here.
log.warning(
f"{name} was missing or already deleted from the machines inventory: {exc}"
)
changed_paths: list[Path] = []