from __future__ import annotations from dataclasses import dataclass, field from pathlib import Path @dataclass(slots=True) class SessionHistory: """In-memory session history for visited directories.""" _entries: list[Path] = field(default_factory=list) _index: int = -1 def visit(self, path: Path) -> Path: """Record a directory visit and discard forward history when needed.""" resolved_path = path.expanduser().resolve() if self.current == resolved_path: return resolved_path if self._index < len(self._entries) - 1: self._entries = self._entries[: self._index + 1] self._entries.append(resolved_path) self._index = len(self._entries) - 1 return resolved_path @property def current(self) -> Path | None: """Return the current history entry.""" if self._index == -1: return None return self._entries[self._index] def back(self) -> Path | None: """Move backward in history when possible.""" if self._index <= 0: return None self._index -= 1 return self._entries[self._index] def forward(self) -> Path | None: """Move forward in history when possible.""" if self._index == -1 or self._index >= len(self._entries) - 1: return None self._index += 1 return self._entries[self._index] def select(self, index: int) -> Path: """Jump to a previously visited directory by history index.""" if index < 0 or index >= len(self._entries): raise IndexError("History index out of range") self._index = index return self._entries[self._index] def entries(self) -> tuple[Path, ...]: """Return the full history as an immutable sequence.""" return tuple(self._entries)