Commit a5092861 authored by Jakob Moser's avatar Jakob Moser
Browse files

Make Vault a context manager

parent 228779fa
Loading
Loading
Loading
Loading
+17 −2
Original line number Diff line number Diff line
from contextlib import AbstractContextManager
from dataclasses import dataclass
from os import getgid, getuid
from pathlib import Path
from subprocess import CalledProcessError, run
from typing import Any, Self
from uuid import uuid4


@dataclass(frozen=True)
class Vault:
class Vault(AbstractContextManager):
    image: Path
    mountpoint: Path

@@ -127,17 +129,30 @@ class Vault:
        except CalledProcessError:
            return False

    def open(self, password: str, create_if_not_exists: bool = True) -> None:
    def open(self, password: str, create_if_not_exists: bool = True) -> Self:
        """
        Open the vault (creating it if desired and necessary) and return self, i.e., the instance.

        This method returns the Vault instance so that it can be used neatly in a `with` statement.
        """
        if create_if_not_exists and not self.exists:
            self.create(password)

        self._cryptsetup_open(password)
        self._mount()

        return self

    def close(self) -> None:
        self._umount()
        self._cryptsetup_close()

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        """
        Ignore any potentially passed exceptions and close the vault.
        """
        self.close()

    @property
    def is_open(self) -> bool:
        return self._is_mounted