Initialize history using history related attributes. :param hist_file: optional path to persistent history file. If specified, then history from previous sessions will be included. Additionally, all history will be written to this file whe
(self, hist_file: str)
| 5303 | return history |
| 5304 | |
| 5305 | def _initialize_history(self, hist_file: str) -> None: |
| 5306 | """Initialize history using history related attributes. |
| 5307 | |
| 5308 | :param hist_file: optional path to persistent history file. If specified, then history from |
| 5309 | previous sessions will be included. Additionally, all history will be written |
| 5310 | to this file when the application exits. |
| 5311 | """ |
| 5312 | self.history = History() |
| 5313 | |
| 5314 | # With no persistent history, nothing else in this method is relevant |
| 5315 | if not hist_file: |
| 5316 | self.persistent_history_file = hist_file |
| 5317 | return |
| 5318 | |
| 5319 | hist_file = os.path.abspath(os.path.expanduser(hist_file)) |
| 5320 | |
| 5321 | # On Windows, trying to open a directory throws a permission |
| 5322 | # error, not a `IsADirectoryError`. So we'll check it ourselves. |
| 5323 | if os.path.isdir(hist_file): |
| 5324 | self.perror(f"Persistent history file '{hist_file}' is a directory") |
| 5325 | return |
| 5326 | |
| 5327 | # Create the directory for the history file if it doesn't already exist |
| 5328 | hist_file_dir = os.path.dirname(hist_file) |
| 5329 | try: |
| 5330 | os.makedirs(hist_file_dir, exist_ok=True) |
| 5331 | except OSError as ex: |
| 5332 | self.perror(f"Error creating persistent history file directory '{hist_file_dir}': {ex}") |
| 5333 | return |
| 5334 | |
| 5335 | # Read history file |
| 5336 | try: |
| 5337 | with open(hist_file, "rb") as fobj: |
| 5338 | compressed_bytes = fobj.read() |
| 5339 | except FileNotFoundError: |
| 5340 | compressed_bytes = b"" |
| 5341 | except OSError as ex: |
| 5342 | self.perror(f"Cannot read persistent history file '{hist_file}': {ex}") |
| 5343 | return |
| 5344 | |
| 5345 | # Register a function to write history at save |
| 5346 | import atexit |
| 5347 | |
| 5348 | self.persistent_history_file = hist_file |
| 5349 | atexit.register(self._persist_history) |
| 5350 | |
| 5351 | # Empty or nonexistent history file. Nothing more to do. |
| 5352 | if not compressed_bytes: |
| 5353 | return |
| 5354 | |
| 5355 | # Decompress history data |
| 5356 | try: |
| 5357 | import lzma as decompress_lib |
| 5358 | |
| 5359 | decompress_exceptions: tuple[type[Exception]] = (decompress_lib.LZMAError,) |
| 5360 | except ModuleNotFoundError: # pragma: no cover |
| 5361 | import bz2 as decompress_lib # type: ignore[no-redef] |
| 5362 |