|
| 1 | +import os |
| 2 | +from typing import Iterable, Union, List, Tuple |
| 3 | + |
| 4 | +from prompt_toolkit.history import FileHistory |
| 5 | + |
| 6 | +_StrOrBytesPath = Union[str, bytes, os.PathLike] |
| 7 | + |
| 8 | + |
| 9 | +class FileHistoryWithTimestamp(FileHistory): |
| 10 | + """ |
| 11 | + :class:`.FileHistory` class that stores all strings in a file with timestamp. |
| 12 | + """ |
| 13 | + |
| 14 | + def __init__(self, filename: _StrOrBytesPath) -> None: |
| 15 | + self.filename = filename |
| 16 | + super().__init__(filename) |
| 17 | + |
| 18 | + def load_history_with_timestamp(self) -> List[Tuple[str, str]]: |
| 19 | + """ |
| 20 | + Load history entries along with their timestamps. |
| 21 | +
|
| 22 | + Returns: |
| 23 | + List[Tuple[str, str]]: A list of tuples where each tuple contains |
| 24 | + a history entry and its corresponding timestamp. |
| 25 | + """ |
| 26 | + history_with_timestamp: List[Tuple[str, str]] = [] |
| 27 | + lines: List[str] = [] |
| 28 | + timestamp: str = "" |
| 29 | + |
| 30 | + def add() -> None: |
| 31 | + if lines: |
| 32 | + # Join and drop trailing newline. |
| 33 | + string = "".join(lines)[:-1] |
| 34 | + history_with_timestamp.append((string, timestamp)) |
| 35 | + |
| 36 | + if os.path.exists(self.filename): |
| 37 | + with open(self.filename, "rb") as f: |
| 38 | + for line_bytes in f: |
| 39 | + line = line_bytes.decode("utf-8", errors="replace") |
| 40 | + |
| 41 | + if line.startswith("#"): |
| 42 | + # Extract timestamp |
| 43 | + timestamp = line[2:].strip() |
| 44 | + elif line.startswith("+"): |
| 45 | + lines.append(line[1:]) |
| 46 | + else: |
| 47 | + add() |
| 48 | + lines = [] |
| 49 | + |
| 50 | + add() |
| 51 | + |
| 52 | + return list(reversed(history_with_timestamp)) |
0 commit comments