:class:`.FileHistory` class that stores all strings in a file with timestamp.
| 9 | |
| 10 | |
| 11 | class FileHistoryWithTimestamp(FileHistory): |
| 12 | """ |
| 13 | :class:`.FileHistory` class that stores all strings in a file with timestamp. |
| 14 | """ |
| 15 | |
| 16 | def __init__(self, filename: _StrOrBytesPath) -> None: |
| 17 | self.filename = filename |
| 18 | super().__init__(filename) |
| 19 | |
| 20 | def append_string(self, string: str) -> None: |
| 21 | "Add string to the history." |
| 22 | self._loaded_strings.insert(0, string) |
| 23 | if is_password_change(string): |
| 24 | return |
| 25 | self.store_string(string) |
| 26 | |
| 27 | def load_history_with_timestamp(self) -> list[tuple[str, str]]: |
| 28 | """ |
| 29 | Load history entries along with their timestamps. |
| 30 | |
| 31 | Returns: |
| 32 | list[tuple[str, str]]: A list of tuples where each tuple contains |
| 33 | a history entry and its corresponding timestamp. |
| 34 | """ |
| 35 | history_with_timestamp: list[tuple[str, str]] = [] |
| 36 | lines: list[str] = [] |
| 37 | timestamp: str = "" |
| 38 | |
| 39 | def add() -> None: |
| 40 | if lines: |
| 41 | # Join and drop trailing newline. |
| 42 | string = "".join(lines)[:-1] |
| 43 | history_with_timestamp.append((string, timestamp)) |
| 44 | |
| 45 | if os.path.exists(self.filename): |
| 46 | with open(self.filename, 'r', encoding='utf-8') as f: |
| 47 | for line in f: |
| 48 | if line.startswith("#"): |
| 49 | # Extract timestamp |
| 50 | timestamp = line[2:].strip() |
| 51 | elif line.startswith("+"): |
| 52 | lines.append(line[1:]) |
| 53 | else: |
| 54 | add() |
| 55 | lines = [] |
| 56 | |
| 57 | add() |
| 58 | |
| 59 | return list(reversed(history_with_timestamp)) |
no outgoing calls