clan-cli: clan_cli.locked_open -> clan_lib.locked_open

This commit is contained in:
lassulus
2025-05-20 14:48:19 +02:00
parent 66415d3943
commit 48595fe7f5
6 changed files with 7 additions and 9 deletions

View File

@@ -1,33 +0,0 @@
import fcntl
import json
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from clan_lib.dirs import user_history_file
from .jsonrpc import ClanJSONEncoder
@contextmanager
def locked_open(filename: Path, mode: str = "r") -> Generator:
"""
This is a context manager that provides an advisory write lock on the file specified by `filename` when entering the context, and releases the lock when leaving the context. The lock is acquired using the `fcntl` module's `LOCK_EX` flag, which applies an exclusive write lock to the file.
"""
with filename.open(mode) as fd:
fcntl.flock(fd, fcntl.LOCK_EX)
yield fd
fcntl.flock(fd, fcntl.LOCK_UN)
def write_history_file(data: Any) -> None:
with locked_open(user_history_file(), "w+") as f:
f.write(json.dumps(data, cls=ClanJSONEncoder, indent=4))
def read_history_file() -> list[dict]:
with locked_open(user_history_file(), "r") as f:
content: str = f.read()
parsed: list[dict] = json.loads(content)
return parsed

View File

@@ -10,7 +10,6 @@ from pathlib import Path
from typing import Any, NamedTuple
import pytest
from clan_cli.locked_open import locked_open
from clan_cli.machines.machines import Machine
from clan_cli.tests import age_keys
from clan_cli.tests.fixture_error import FixtureError
@@ -23,6 +22,7 @@ from clan_lib.dirs import (
specific_machine_dir,
)
from clan_lib.flake import Flake
from clan_lib.locked_open import locked_open
from clan_lib.nix import nix_test_store
log = logging.getLogger(__name__)

View File

@@ -5,7 +5,6 @@ from pathlib import Path
from typing import Any
import pytest
from clan_cli.locked_open import locked_open
from clan_cli.templates import (
ClanExports,
InputName,
@@ -19,6 +18,7 @@ from clan_cli.tests.fixtures_flakes import FlakeForTest
from clan_lib.cmd import run
from clan_lib.flake import Flake
from clan_lib.git import commit_file
from clan_lib.locked_open import locked_open
from clan_lib.nix import nix_command