Files
ProgressQuest-cli/pqcli/roster.py
T
Dash 0a4358e2b8 misc: drop typing as T, use builtin generics
Python 3.10 is the minimum, so annotations use `X | None`, `list[X]`
and friends, enforced by ruff's pyupgrade rules. The remaining typing
names are imported directly, with abstract types coming from
collections.abc. first() is now generic over the item and default.
2026-10-17 15:55:55 +02:00

40 lines
1.2 KiB
Python

import logging
import pickle
from datetime import datetime
from pathlib import Path
from pqcli.mechanic import Player
class Roster:
def __init__(self, path: Path, players: list[Player]) -> None:
self.path = path
self.players = players
self._last_save = datetime.now()
@staticmethod
def load(path: str | Path) -> "Roster":
real_path = Path(path)
if real_path.exists():
return Roster(
real_path, players=pickle.loads(real_path.read_bytes())
)
return Roster(real_path, players=[])
def save(self) -> None:
self._last_save = datetime.now()
old_path = self.path.with_name(self.path.name + ".old")
tmp_path = self.path.with_name(self.path.name + ".new")
tmp_path.parent.mkdir(parents=True, exist_ok=True)
tmp_path.write_bytes(pickle.dumps(self.players))
if self.path.exists():
if old_path.exists():
old_path.unlink()
self.path.rename(old_path)
tmp_path.rename(self.path)
def save_periodically(self) -> None:
if (datetime.now() - self._last_save).total_seconds() >= 300:
logging.info("Saving...")
self.save()