| 1 |
"""History related magics and functionality""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
# Copyright (c) IPython Development Team. |
| 6 |
# Distributed under the terms of the Modified BSD License. |
| 7 |
|
| 8 |
|
| 9 |
import atexit |
| 10 |
import datetime |
| 11 |
import os |
| 12 |
import re |
| 13 |
|
| 14 |
|
| 15 |
import threading |
| 16 |
from pathlib import Path |
| 17 |
|
| 18 |
from collections import defaultdict |
| 19 |
from contextlib import contextmanager |
| 20 |
from dataclasses import dataclass |
| 21 |
from decorator import decorator |
| 22 |
from traitlets import ( |
| 23 |
Any, |
| 24 |
Bool, |
| 25 |
Dict, |
| 26 |
Instance, |
| 27 |
Integer, |
| 28 |
List, |
| 29 |
TraitError, |
| 30 |
Unicode, |
| 31 |
Union, |
| 32 |
default, |
| 33 |
observe, |
| 34 |
) |
| 35 |
from traitlets.config.configurable import LoggingConfigurable |
| 36 |
|
| 37 |
from IPython.paths import locate_profile |
| 38 |
from IPython.utils.decorators import undoc |
| 39 |
from typing import Tuple, Optional, TYPE_CHECKING |
| 40 |
from collections.abc import Iterable |
| 41 |
import typing |
| 42 |
import typing as t |
| 43 |
from typing import cast |
| 44 |
from warnings import warn |
| 45 |
from weakref import ref, WeakSet |
| 46 |
|
| 47 |
if TYPE_CHECKING: |
| 48 |
from IPython.core.interactiveshell import InteractiveShell |
| 49 |
from IPython.config.Configuration import Configuration |
| 50 |
|
| 51 |
try: |
| 52 |
from sqlite3 import DatabaseError, OperationalError |
| 53 |
import sqlite3 |
| 54 |
|
| 55 |
sqlite3.register_converter( |
| 56 |
"timestamp", lambda val: datetime.datetime.fromisoformat(val.decode()) |
| 57 |
) |
| 58 |
|
| 59 |
sqlite3_found = True |
| 60 |
except ModuleNotFoundError: |
| 61 |
sqlite3_found = False |
| 62 |
|
| 63 |
class DatabaseError(Exception): # type: ignore [no-redef] |
| 64 |
pass |
| 65 |
|
| 66 |
class OperationalError(Exception): # type: ignore [no-redef] |
| 67 |
pass |
| 68 |
|
| 69 |
|
| 70 |
InOrInOut = typing.Union[str, tuple[str, Optional[str]]] |
| 71 |
|
| 72 |
# ----------------------------------------------------------------------------- |
| 73 |
# Classes and functions |
| 74 |
# ----------------------------------------------------------------------------- |
| 75 |
|
| 76 |
|
| 77 |
@undoc |
| 78 |
class DummyDB: |
| 79 |
"""Dummy DB that will act as a black hole for history. |
| 80 |
|
| 81 |
Only used in the absence of sqlite""" |
| 82 |
|
| 83 |
def execute(*args: typing.Any, **kwargs: typing.Any) -> list: |
| 84 |
return [] |
| 85 |
|
| 86 |
def commit(self, *args, **kwargs): # type: ignore [no-untyped-def] |
| 87 |
pass |
| 88 |
|
| 89 |
def __enter__(self, *args, **kwargs): # type: ignore [no-untyped-def] |
| 90 |
pass |
| 91 |
|
| 92 |
def __exit__(self, *args, **kwargs): # type: ignore [no-untyped-def] |
| 93 |
pass |
| 94 |
|
| 95 |
def close(self, *args, **kwargs): # type: ignore [no-untyped-def] |
| 96 |
pass |
| 97 |
|
| 98 |
|
| 99 |
@decorator |
| 100 |
def only_when_enabled(f, self, *a, **kw): # type: ignore [no-untyped-def] |
| 101 |
"""Decorator: return an empty list in the absence of sqlite.""" |
| 102 |
if not self.enabled: |
| 103 |
return [] |
| 104 |
else: |
| 105 |
return f(self, *a, **kw) |
| 106 |
|
| 107 |
|
| 108 |
# use 16kB as threshold for whether a corrupt history db should be saved |
| 109 |
# that should be at least 100 entries or so |
| 110 |
_SAVE_DB_SIZE = 16384 |
| 111 |
|
| 112 |
|
| 113 |
@decorator |
| 114 |
def catch_corrupt_db(f, self, *a, **kw): # type: ignore [no-untyped-def] |
| 115 |
"""A decorator which wraps HistoryAccessor method calls to catch errors from |
| 116 |
a corrupt SQLite database, move the old database out of the way, and create |
| 117 |
a new one. |
| 118 |
|
| 119 |
We avoid clobbering larger databases because this may be triggered due to filesystem issues, |
| 120 |
not just a corrupt file. |
| 121 |
""" |
| 122 |
try: |
| 123 |
return f(self, *a, **kw) |
| 124 |
except (DatabaseError, OperationalError) as e: |
| 125 |
self._corrupt_db_counter += 1 |
| 126 |
self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e) |
| 127 |
if self.hist_file != ":memory:": |
| 128 |
if self._corrupt_db_counter > self._corrupt_db_limit: |
| 129 |
self.hist_file = ":memory:" |
| 130 |
self.log.error( |
| 131 |
"Failed to load history too many times, history will not be saved." |
| 132 |
) |
| 133 |
elif self.hist_file.is_file(): |
| 134 |
# move the file out of the way |
| 135 |
base = str(self.hist_file.parent / self.hist_file.stem) |
| 136 |
ext = self.hist_file.suffix |
| 137 |
size = self.hist_file.stat().st_size |
| 138 |
if size >= _SAVE_DB_SIZE: |
| 139 |
# if there's significant content, avoid clobbering |
| 140 |
now = ( |
| 141 |
datetime.datetime.now(datetime.timezone.utc) |
| 142 |
.isoformat() |
| 143 |
.replace(":", ".") |
| 144 |
) |
| 145 |
newpath = base + "-corrupt-" + now + ext |
| 146 |
# don't clobber previous corrupt backups |
| 147 |
for i in range(100): |
| 148 |
if not Path(newpath).exists(): |
| 149 |
break |
| 150 |
else: |
| 151 |
newpath = base + "-corrupt-" + now + ("-%i" % i) + ext |
| 152 |
else: |
| 153 |
# not much content, possibly empty; don't worry about clobbering |
| 154 |
# maybe we should just delete it? |
| 155 |
newpath = base + "-corrupt" + ext |
| 156 |
self.hist_file.rename(newpath) |
| 157 |
self.log.error( |
| 158 |
"History file was moved to %s and a new file created.", newpath |
| 159 |
) |
| 160 |
self.init_db() |
| 161 |
return [] |
| 162 |
else: |
| 163 |
# Failed with :memory:, something serious is wrong |
| 164 |
raise |
| 165 |
|
| 166 |
|
| 167 |
class HistoryAccessorBase(LoggingConfigurable): |
| 168 |
"""An abstract class for History Accessors""" |
| 169 |
|
| 170 |
def get_tail( |
| 171 |
self, |
| 172 |
n: int = 10, |
| 173 |
raw: bool = True, |
| 174 |
output: bool = False, |
| 175 |
include_latest: bool = False, |
| 176 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 177 |
raise NotImplementedError |
| 178 |
|
| 179 |
def search( |
| 180 |
self, |
| 181 |
pattern: str = "*", |
| 182 |
raw: bool = True, |
| 183 |
search_raw: bool = True, |
| 184 |
output: bool = False, |
| 185 |
n: Optional[int] = None, |
| 186 |
unique: bool = False, |
| 187 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 188 |
raise NotImplementedError |
| 189 |
|
| 190 |
def get_range( |
| 191 |
self, |
| 192 |
session: int, |
| 193 |
start: int = 1, |
| 194 |
stop: Optional[int] = None, |
| 195 |
raw: bool = True, |
| 196 |
output: bool = False, |
| 197 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 198 |
raise NotImplementedError |
| 199 |
|
| 200 |
def get_range_by_str( |
| 201 |
self, rangestr: str, raw: bool = True, output: bool = False |
| 202 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 203 |
raise NotImplementedError |
| 204 |
|
| 205 |
|
| 206 |
class HistoryAccessor(HistoryAccessorBase): |
| 207 |
"""Access the history database without adding to it. |
| 208 |
|
| 209 |
This is intended for use by standalone history tools. IPython shells use |
| 210 |
HistoryManager, below, which is a subclass of this.""" |
| 211 |
|
| 212 |
# counter for init_db retries, so we don't keep trying over and over |
| 213 |
_corrupt_db_counter = 0 |
| 214 |
# after two failures, fallback on :memory: |
| 215 |
_corrupt_db_limit = 2 |
| 216 |
|
| 217 |
# String holding the path to the history file |
| 218 |
hist_file = Union( |
| 219 |
[Instance(Path), Unicode()], |
| 220 |
help="""Path to file to use for SQLite history database. |
| 221 |
|
| 222 |
By default, IPython will put the history database in the IPython |
| 223 |
profile directory. If you would rather share one history among |
| 224 |
profiles, you can set this value in each, so that they are consistent. |
| 225 |
|
| 226 |
Due to an issue with fcntl, SQLite is known to misbehave on some NFS |
| 227 |
mounts. If you see IPython hanging, try setting this to something on a |
| 228 |
local disk, e.g:: |
| 229 |
|
| 230 |
ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite |
| 231 |
|
| 232 |
you can also use the specific value `:memory:` (including the colon |
| 233 |
at both end but not the back ticks), to avoid creating an history file. |
| 234 |
|
| 235 |
""", |
| 236 |
).tag(config=True) |
| 237 |
|
| 238 |
enabled = Bool( |
| 239 |
sqlite3_found, |
| 240 |
help="""enable the SQLite history |
| 241 |
|
| 242 |
set enabled=False to disable the SQLite history, |
| 243 |
in which case there will be no stored history, no SQLite connection, |
| 244 |
and no background saving thread. This may be necessary in some |
| 245 |
threaded environments where IPython is embedded. |
| 246 |
""", |
| 247 |
).tag(config=True) |
| 248 |
|
| 249 |
connection_options = Dict( |
| 250 |
help="""Options for configuring the SQLite connection |
| 251 |
|
| 252 |
These options are passed as keyword args to sqlite3.connect |
| 253 |
when establishing database connections. |
| 254 |
""" |
| 255 |
).tag(config=True) |
| 256 |
|
| 257 |
@default("connection_options") |
| 258 |
def _default_connection_options(self) -> dict[str, bool]: |
| 259 |
return dict(check_same_thread=False) |
| 260 |
|
| 261 |
# The SQLite database |
| 262 |
db = Any() |
| 263 |
|
| 264 |
@observe("db") |
| 265 |
@only_when_enabled |
| 266 |
def _db_changed(self, change): # type: ignore [no-untyped-def] |
| 267 |
"""validate the db, since it can be an Instance of two different types""" |
| 268 |
new = change["new"] |
| 269 |
connection_types = (DummyDB, sqlite3.Connection) |
| 270 |
if not isinstance(new, connection_types): |
| 271 |
msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % ( |
| 272 |
self.__class__.__name__, |
| 273 |
new, |
| 274 |
) |
| 275 |
raise TraitError(msg) |
| 276 |
|
| 277 |
def __init__( |
| 278 |
self, profile: str = "default", hist_file: str = "", **traits: typing.Any |
| 279 |
) -> None: |
| 280 |
"""Create a new history accessor. |
| 281 |
|
| 282 |
Parameters |
| 283 |
---------- |
| 284 |
profile : str |
| 285 |
The name of the profile from which to open history. |
| 286 |
hist_file : str |
| 287 |
Path to an SQLite history database stored by IPython. If specified, |
| 288 |
hist_file overrides profile. |
| 289 |
config : :class:`~traitlets.config.loader.Config` |
| 290 |
Config object. hist_file can also be set through this. |
| 291 |
""" |
| 292 |
super(HistoryAccessor, self).__init__(**traits) |
| 293 |
# defer setting hist_file from kwarg until after init, |
| 294 |
# otherwise the default kwarg value would clobber any value |
| 295 |
# set by config |
| 296 |
if hist_file: |
| 297 |
self.hist_file = hist_file |
| 298 |
|
| 299 |
try: |
| 300 |
self.hist_file |
| 301 |
except TraitError: |
| 302 |
# No one has set the hist_file, yet. |
| 303 |
self.hist_file = self._get_hist_file_name(profile) |
| 304 |
|
| 305 |
self.init_db() |
| 306 |
|
| 307 |
def _get_hist_file_name(self, profile: str = "default") -> Path: |
| 308 |
"""Find the history file for the given profile name. |
| 309 |
|
| 310 |
This is overridden by the HistoryManager subclass, to use the shell's |
| 311 |
active profile. |
| 312 |
|
| 313 |
Parameters |
| 314 |
---------- |
| 315 |
profile : str |
| 316 |
The name of a profile which has a history file. |
| 317 |
""" |
| 318 |
return Path(locate_profile(profile)) / "history.sqlite" |
| 319 |
|
| 320 |
@catch_corrupt_db |
| 321 |
def init_db(self) -> None: |
| 322 |
"""Connect to the database, and create tables if necessary.""" |
| 323 |
if not self.enabled: |
| 324 |
self.db = DummyDB() |
| 325 |
return |
| 326 |
|
| 327 |
# use detect_types so that timestamps return datetime objects |
| 328 |
kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) |
| 329 |
kwargs.update(self.connection_options) |
| 330 |
self.db = sqlite3.connect(str(self.hist_file), **kwargs) # type: ignore [call-overload] |
| 331 |
with self.db: |
| 332 |
self.db.execute( |
| 333 |
"""CREATE TABLE IF NOT EXISTS sessions (session integer |
| 334 |
primary key autoincrement, start timestamp, |
| 335 |
end timestamp, num_cmds integer, remark text)""" |
| 336 |
) |
| 337 |
self.db.execute( |
| 338 |
"""CREATE TABLE IF NOT EXISTS history |
| 339 |
(session integer, line integer, source text, source_raw text, |
| 340 |
PRIMARY KEY (session, line))""" |
| 341 |
) |
| 342 |
# Output history is optional, but ensure the table's there so it can be |
| 343 |
# enabled later. |
| 344 |
self.db.execute( |
| 345 |
"""CREATE TABLE IF NOT EXISTS output_history |
| 346 |
(session integer, line integer, output text, |
| 347 |
PRIMARY KEY (session, line))""" |
| 348 |
) |
| 349 |
# success! reset corrupt db count |
| 350 |
self._corrupt_db_counter = 0 |
| 351 |
|
| 352 |
def __del__(self) -> None: |
| 353 |
if hasattr(self, "db"): |
| 354 |
self.db.close() |
| 355 |
|
| 356 |
def writeout_cache(self) -> None: |
| 357 |
"""Overridden by HistoryManager to dump the cache before certain |
| 358 |
database lookups.""" |
| 359 |
pass |
| 360 |
|
| 361 |
## ------------------------------- |
| 362 |
## Methods for retrieving history: |
| 363 |
## ------------------------------- |
| 364 |
def _run_sql( |
| 365 |
self, |
| 366 |
sql: str, |
| 367 |
params: tuple, |
| 368 |
raw: bool = True, |
| 369 |
output: bool = False, |
| 370 |
latest: bool = False, |
| 371 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 372 |
"""Prepares and runs an SQL query for the history database. |
| 373 |
|
| 374 |
Parameters |
| 375 |
---------- |
| 376 |
sql : str |
| 377 |
Any filtering expressions to go after SELECT ... FROM ... |
| 378 |
params : tuple |
| 379 |
Parameters passed to the SQL query (to replace "?") |
| 380 |
raw, output : bool |
| 381 |
See :meth:`get_range` |
| 382 |
latest : bool |
| 383 |
Select rows with max (session, line) |
| 384 |
|
| 385 |
Returns |
| 386 |
------- |
| 387 |
Tuples as :meth:`get_range` |
| 388 |
""" |
| 389 |
toget = "source_raw" if raw else "source" |
| 390 |
sqlfrom = "history" |
| 391 |
if output: |
| 392 |
sqlfrom = "history LEFT JOIN output_history USING (session, line)" |
| 393 |
toget = "history.%s, output_history.output" % toget |
| 394 |
if latest: |
| 395 |
toget += ", MAX(session * 128 * 1024 + line)" |
| 396 |
this_querry = "SELECT session, line, %s FROM %s " % (toget, sqlfrom) + sql |
| 397 |
cur = self.db.execute(this_querry, params) |
| 398 |
if latest: |
| 399 |
cur = (row[:-1] for row in cur) |
| 400 |
if output: # Regroup into 3-tuples, and parse JSON |
| 401 |
return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) |
| 402 |
return cur |
| 403 |
|
| 404 |
@only_when_enabled |
| 405 |
@catch_corrupt_db |
| 406 |
def get_session_info( |
| 407 |
self, session: int |
| 408 |
) -> tuple[int, datetime.datetime, Optional[datetime.datetime], Optional[int], str]: |
| 409 |
"""Get info about a session. |
| 410 |
|
| 411 |
Parameters |
| 412 |
---------- |
| 413 |
session : int |
| 414 |
Session number to retrieve. |
| 415 |
|
| 416 |
Returns |
| 417 |
------- |
| 418 |
session_id : int |
| 419 |
Session ID number |
| 420 |
start : datetime |
| 421 |
Timestamp for the start of the session. |
| 422 |
end : datetime |
| 423 |
Timestamp for the end of the session, or None if IPython crashed. |
| 424 |
num_cmds : int |
| 425 |
Number of commands run, or None if IPython crashed. |
| 426 |
remark : str |
| 427 |
A manually set description. |
| 428 |
""" |
| 429 |
query = "SELECT * from sessions where session == ?" |
| 430 |
return self.db.execute(query, (session,)).fetchone() |
| 431 |
|
| 432 |
@catch_corrupt_db |
| 433 |
def get_last_session_id(self) -> Optional[int]: |
| 434 |
"""Get the last session ID currently in the database. |
| 435 |
|
| 436 |
Within IPython, this should be the same as the value stored in |
| 437 |
:attr:`HistoryManager.session_number`. |
| 438 |
""" |
| 439 |
for record in self.get_tail(n=1, include_latest=True): |
| 440 |
return record[0] |
| 441 |
return None |
| 442 |
|
| 443 |
@catch_corrupt_db |
| 444 |
def get_tail( |
| 445 |
self, |
| 446 |
n: int = 10, |
| 447 |
raw: bool = True, |
| 448 |
output: bool = False, |
| 449 |
include_latest: bool = False, |
| 450 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 451 |
"""Get the last n lines from the history database. |
| 452 |
|
| 453 |
Parameters |
| 454 |
---------- |
| 455 |
n : int |
| 456 |
The number of lines to get |
| 457 |
raw, output : bool |
| 458 |
See :meth:`get_range` |
| 459 |
include_latest : bool |
| 460 |
If False (default), n+1 lines are fetched, and the latest one |
| 461 |
is discarded. This is intended to be used where the function |
| 462 |
is called by a user command, which it should not return. |
| 463 |
|
| 464 |
Returns |
| 465 |
------- |
| 466 |
Tuples as :meth:`get_range` |
| 467 |
""" |
| 468 |
self.writeout_cache() |
| 469 |
if not include_latest: |
| 470 |
n += 1 |
| 471 |
cur = self._run_sql( |
| 472 |
"ORDER BY session DESC, line DESC LIMIT ?", (n,), raw=raw, output=output |
| 473 |
) |
| 474 |
if not include_latest: |
| 475 |
return reversed(list(cur)[1:]) |
| 476 |
return reversed(list(cur)) |
| 477 |
|
| 478 |
@catch_corrupt_db |
| 479 |
def search( |
| 480 |
self, |
| 481 |
pattern: str = "*", |
| 482 |
raw: bool = True, |
| 483 |
search_raw: bool = True, |
| 484 |
output: bool = False, |
| 485 |
n: Optional[int] = None, |
| 486 |
unique: bool = False, |
| 487 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 488 |
"""Search the database using unix glob-style matching (wildcards |
| 489 |
* and ?). |
| 490 |
|
| 491 |
Parameters |
| 492 |
---------- |
| 493 |
pattern : str |
| 494 |
The wildcarded pattern to match when searching |
| 495 |
search_raw : bool |
| 496 |
If True, search the raw input, otherwise, the parsed input |
| 497 |
raw, output : bool |
| 498 |
See :meth:`get_range` |
| 499 |
n : None or int |
| 500 |
If an integer is given, it defines the limit of |
| 501 |
returned entries. |
| 502 |
unique : bool |
| 503 |
When it is true, return only unique entries. |
| 504 |
|
| 505 |
Returns |
| 506 |
------- |
| 507 |
Tuples as :meth:`get_range` |
| 508 |
""" |
| 509 |
tosearch = "source_raw" if search_raw else "source" |
| 510 |
if output: |
| 511 |
tosearch = "history." + tosearch |
| 512 |
self.writeout_cache() |
| 513 |
sqlform = "WHERE %s GLOB ?" % tosearch |
| 514 |
params: tuple[typing.Any, ...] = (pattern,) |
| 515 |
if unique: |
| 516 |
sqlform += " GROUP BY {0}".format(tosearch) |
| 517 |
if n is not None: |
| 518 |
sqlform += " ORDER BY session DESC, line DESC LIMIT ?" |
| 519 |
params += (n,) |
| 520 |
elif unique: |
| 521 |
sqlform += " ORDER BY session, line" |
| 522 |
cur = self._run_sql(sqlform, params, raw=raw, output=output, latest=unique) |
| 523 |
if n is not None: |
| 524 |
return reversed(list(cur)) |
| 525 |
return cur |
| 526 |
|
| 527 |
@catch_corrupt_db |
| 528 |
def get_range( |
| 529 |
self, |
| 530 |
session: int, |
| 531 |
start: int = 1, |
| 532 |
stop: Optional[int] = None, |
| 533 |
raw: bool = True, |
| 534 |
output: bool = False, |
| 535 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 536 |
"""Retrieve input by session. |
| 537 |
|
| 538 |
Parameters |
| 539 |
---------- |
| 540 |
session : int |
| 541 |
Session number to retrieve. |
| 542 |
start : int |
| 543 |
First line to retrieve. |
| 544 |
stop : int |
| 545 |
End of line range (excluded from output itself). If None, retrieve |
| 546 |
to the end of the session. |
| 547 |
raw : bool |
| 548 |
If True, return untranslated input |
| 549 |
output : bool |
| 550 |
If True, attempt to include output. This will be 'real' Python |
| 551 |
objects for the current session, or text reprs from previous |
| 552 |
sessions if db_log_output was enabled at the time. Where no output |
| 553 |
is found, None is used. |
| 554 |
|
| 555 |
Returns |
| 556 |
------- |
| 557 |
entries |
| 558 |
An iterator over the desired lines. Each line is a 3-tuple, either |
| 559 |
(session, line, input) if output is False, or |
| 560 |
(session, line, (input, output)) if output is True. |
| 561 |
""" |
| 562 |
params: tuple[typing.Any, ...] |
| 563 |
if stop: |
| 564 |
lineclause = "line >= ? AND line < ?" |
| 565 |
params = (session, start, stop) |
| 566 |
else: |
| 567 |
lineclause = "line>=?" |
| 568 |
params = (session, start) |
| 569 |
|
| 570 |
return self._run_sql( |
| 571 |
"WHERE session==? AND %s" % lineclause, params, raw=raw, output=output |
| 572 |
) |
| 573 |
|
| 574 |
def get_range_by_str( |
| 575 |
self, rangestr: str, raw: bool = True, output: bool = False |
| 576 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 577 |
"""Get lines of history from a string of ranges, as used by magic |
| 578 |
commands %hist, %save, %macro, etc. |
| 579 |
|
| 580 |
Parameters |
| 581 |
---------- |
| 582 |
rangestr : str |
| 583 |
A string specifying ranges, e.g. "5 ~2/1-4". If empty string is used, |
| 584 |
this will return everything from current session's history. |
| 585 |
|
| 586 |
See the documentation of :func:`%history` for the full details. |
| 587 |
|
| 588 |
raw, output : bool |
| 589 |
As :meth:`get_range` |
| 590 |
|
| 591 |
Returns |
| 592 |
------- |
| 593 |
Tuples as :meth:`get_range` |
| 594 |
""" |
| 595 |
for sess, s, e in extract_hist_ranges(rangestr): |
| 596 |
yield from self.get_range(sess, s, e, raw=raw, output=output) |
| 597 |
|
| 598 |
|
| 599 |
@dataclass |
| 600 |
class HistoryOutput: |
| 601 |
output_type: typing.Literal[ |
| 602 |
"out_stream", "err_stream", "display_data", "execute_result" |
| 603 |
] |
| 604 |
bundle: typing.Dict[str, str | list[str]] |
| 605 |
|
| 606 |
|
| 607 |
class HistoryManager(HistoryAccessor): |
| 608 |
"""A class to organize all history-related functionality in one place.""" |
| 609 |
|
| 610 |
# Public interface |
| 611 |
|
| 612 |
# An instance of the IPython shell we are attached to |
| 613 |
shell = Instance( |
| 614 |
"IPython.core.interactiveshell.InteractiveShellABC", allow_none=False |
| 615 |
) |
| 616 |
# Lists to hold processed and raw history. These start with a blank entry |
| 617 |
# so that we can index them starting from 1 |
| 618 |
input_hist_parsed = List([""]) |
| 619 |
input_hist_raw = List([""]) |
| 620 |
# A list of directories visited during session |
| 621 |
dir_hist: List = List() |
| 622 |
|
| 623 |
@default("dir_hist") |
| 624 |
def _dir_hist_default(self) -> list[Path]: |
| 625 |
try: |
| 626 |
return [Path.cwd()] |
| 627 |
except OSError: |
| 628 |
return [] |
| 629 |
|
| 630 |
# A dict of output history, keyed with ints from the shell's |
| 631 |
# execution count. |
| 632 |
output_hist = Dict() |
| 633 |
# The text/plain repr of outputs. |
| 634 |
output_hist_reprs: typing.Dict[int, str] = Dict() # type: ignore [assignment] |
| 635 |
# Maps execution_count to MIME bundles |
| 636 |
outputs: typing.Dict[int, typing.List[HistoryOutput]] = defaultdict(list) |
| 637 |
# Maps execution_count to exception tracebacks |
| 638 |
exceptions: typing.Dict[int, typing.Dict[str, Any]] = Dict() # type: ignore [assignment] |
| 639 |
|
| 640 |
# The number of the current session in the history database |
| 641 |
session_number: int = Integer() # type: ignore [assignment] |
| 642 |
|
| 643 |
db_log_output = Bool( |
| 644 |
False, help="Should the history database include output? (default: no)" |
| 645 |
).tag(config=True) |
| 646 |
db_cache_size = Integer( |
| 647 |
0, |
| 648 |
help="Write to database every x commands (higher values save disk access & power).\n" |
| 649 |
"Values of 1 or less effectively disable caching.", |
| 650 |
).tag(config=True) |
| 651 |
# The input and output caches |
| 652 |
db_input_cache: List[tuple[int, str, str]] = List() |
| 653 |
db_output_cache: List[tuple[int, str]] = List() |
| 654 |
|
| 655 |
# History saving in separate thread |
| 656 |
save_thread = Instance("IPython.core.history.HistorySavingThread", allow_none=True) |
| 657 |
|
| 658 |
@property |
| 659 |
def save_flag(self) -> threading.Event | None: |
| 660 |
if self.save_thread is not None: |
| 661 |
return self.save_thread.save_flag |
| 662 |
return None |
| 663 |
|
| 664 |
# Private interface |
| 665 |
# Variables used to store the three last inputs from the user. On each new |
| 666 |
# history update, we populate the user's namespace with these, shifted as |
| 667 |
# necessary. |
| 668 |
_i00 = Unicode("") |
| 669 |
_i = Unicode("") |
| 670 |
_ii = Unicode("") |
| 671 |
_iii = Unicode("") |
| 672 |
|
| 673 |
# A regex matching all forms of the exit command, so that we don't store |
| 674 |
# them in the history (it's annoying to rewind the first entry and land on |
| 675 |
# an exit call). |
| 676 |
_exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") |
| 677 |
|
| 678 |
_instances: WeakSet[HistoryManager] = WeakSet() |
| 679 |
_max_inst: int | float = float("inf") |
| 680 |
|
| 681 |
def __init__( |
| 682 |
self, |
| 683 |
shell: InteractiveShell, |
| 684 |
config: Optional[Configuration] = None, |
| 685 |
**traits: typing.Any, |
| 686 |
): |
| 687 |
"""Create a new history manager associated with a shell instance.""" |
| 688 |
super().__init__(shell=shell, config=config, **traits) |
| 689 |
self.db_input_cache_lock = threading.Lock() |
| 690 |
self.db_output_cache_lock = threading.Lock() |
| 691 |
|
| 692 |
try: |
| 693 |
self.new_session() |
| 694 |
except OperationalError: |
| 695 |
self.log.error( |
| 696 |
"Failed to create history session in %s. History will not be saved.", |
| 697 |
self.hist_file, |
| 698 |
exc_info=True, |
| 699 |
) |
| 700 |
self.hist_file = ":memory:" |
| 701 |
|
| 702 |
self.using_thread = False |
| 703 |
if self.enabled and self.hist_file != ":memory:": |
| 704 |
self.save_thread = HistorySavingThread(self) |
| 705 |
try: |
| 706 |
self.save_thread.start() |
| 707 |
except RuntimeError: |
| 708 |
self.log.error( |
| 709 |
"Failed to start history saving thread. History will not be saved.", |
| 710 |
exc_info=True, |
| 711 |
) |
| 712 |
self.hist_file = ":memory:" |
| 713 |
else: |
| 714 |
self.using_thread = True |
| 715 |
self._instances.add(self) |
| 716 |
assert len(HistoryManager._instances) <= HistoryManager._max_inst, ( |
| 717 |
len(HistoryManager._instances), |
| 718 |
HistoryManager._max_inst, |
| 719 |
) |
| 720 |
|
| 721 |
def __del__(self) -> None: |
| 722 |
if self.save_thread is not None: |
| 723 |
self.save_thread.stop() |
| 724 |
HistoryAccessor.__del__(self) |
| 725 |
|
| 726 |
@classmethod |
| 727 |
def _stop_thread(cls) -> None: |
| 728 |
# Used before forking so the thread isn't running at fork |
| 729 |
for inst in cls._instances: |
| 730 |
if inst.save_thread is not None: |
| 731 |
inst.save_thread.stop() |
| 732 |
inst.save_thread = None |
| 733 |
|
| 734 |
def _restart_thread_if_stopped(self) -> None: |
| 735 |
# Start the thread again after it was stopped for forking |
| 736 |
if self.save_thread is None and self.using_thread: |
| 737 |
self.save_thread = HistorySavingThread(self) |
| 738 |
self.save_thread.start() |
| 739 |
|
| 740 |
def _get_hist_file_name(self, profile: Optional[str] = None) -> Path: |
| 741 |
"""Get default history file name based on the Shell's profile. |
| 742 |
|
| 743 |
The profile parameter is ignored, but must exist for compatibility with |
| 744 |
the parent class.""" |
| 745 |
profile_dir = self.shell.profile_dir.location |
| 746 |
return Path(profile_dir) / "history.sqlite" |
| 747 |
|
| 748 |
@only_when_enabled |
| 749 |
def new_session(self, conn: Optional[sqlite3.Connection] = None) -> None: |
| 750 |
"""Get a new session number.""" |
| 751 |
if conn is None: |
| 752 |
conn = self.db |
| 753 |
|
| 754 |
with conn: |
| 755 |
cur = conn.execute( |
| 756 |
"""INSERT INTO sessions VALUES (NULL, ?, NULL, |
| 757 |
NULL, '') """, |
| 758 |
(datetime.datetime.now().isoformat(" "),), |
| 759 |
) |
| 760 |
assert isinstance(cur.lastrowid, int) |
| 761 |
self.session_number = cur.lastrowid |
| 762 |
|
| 763 |
def end_session(self) -> None: |
| 764 |
"""Close the database session, filling in the end time and line count.""" |
| 765 |
self.writeout_cache() |
| 766 |
with self.db: |
| 767 |
self.db.execute( |
| 768 |
"""UPDATE sessions SET end=?, num_cmds=? WHERE |
| 769 |
session==?""", |
| 770 |
( |
| 771 |
datetime.datetime.now(datetime.timezone.utc).isoformat(" "), |
| 772 |
len(self.input_hist_parsed) - 1, |
| 773 |
self.session_number, |
| 774 |
), |
| 775 |
) |
| 776 |
self.session_number = 0 |
| 777 |
|
| 778 |
def name_session(self, name: str) -> None: |
| 779 |
"""Give the current session a name in the history database.""" |
| 780 |
warn( |
| 781 |
"name_session is deprecated in IPython 9.0 and will be removed in future versions", |
| 782 |
DeprecationWarning, |
| 783 |
stacklevel=2, |
| 784 |
) |
| 785 |
with self.db: |
| 786 |
self.db.execute( |
| 787 |
"UPDATE sessions SET remark=? WHERE session==?", |
| 788 |
(name, self.session_number), |
| 789 |
) |
| 790 |
|
| 791 |
def reset(self, new_session: bool = True) -> None: |
| 792 |
"""Clear the session history, releasing all object references, and |
| 793 |
optionally open a new session.""" |
| 794 |
self.output_hist.clear() |
| 795 |
self.outputs.clear() |
| 796 |
self.exceptions.clear() |
| 797 |
|
| 798 |
# The directory history can't be completely empty |
| 799 |
self.dir_hist[:] = [Path.cwd()] |
| 800 |
|
| 801 |
if new_session: |
| 802 |
if self.session_number: |
| 803 |
self.end_session() |
| 804 |
self.input_hist_parsed[:] = [""] |
| 805 |
self.input_hist_raw[:] = [""] |
| 806 |
self.new_session() |
| 807 |
|
| 808 |
# ------------------------------ |
| 809 |
# Methods for retrieving history |
| 810 |
# ------------------------------ |
| 811 |
def get_session_info( |
| 812 |
self, session: int = 0 |
| 813 |
) -> tuple[int, datetime.datetime, Optional[datetime.datetime], Optional[int], str]: |
| 814 |
"""Get info about a session. |
| 815 |
|
| 816 |
Parameters |
| 817 |
---------- |
| 818 |
session : int |
| 819 |
Session number to retrieve. The current session is 0, and negative |
| 820 |
numbers count back from current session, so -1 is the previous session. |
| 821 |
|
| 822 |
Returns |
| 823 |
------- |
| 824 |
session_id : int |
| 825 |
Session ID number |
| 826 |
start : datetime |
| 827 |
Timestamp for the start of the session. |
| 828 |
end : datetime |
| 829 |
Timestamp for the end of the session, or None if IPython crashed. |
| 830 |
num_cmds : int |
| 831 |
Number of commands run, or None if IPython crashed. |
| 832 |
remark : str |
| 833 |
A manually set description. |
| 834 |
""" |
| 835 |
if session <= 0: |
| 836 |
session += self.session_number |
| 837 |
|
| 838 |
return super(HistoryManager, self).get_session_info(session=session) |
| 839 |
|
| 840 |
@catch_corrupt_db |
| 841 |
def get_tail( |
| 842 |
self, |
| 843 |
n: int = 10, |
| 844 |
raw: bool = True, |
| 845 |
output: bool = False, |
| 846 |
include_latest: bool = False, |
| 847 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 848 |
"""Get the last n lines from the history database. |
| 849 |
|
| 850 |
Most recent entry last. |
| 851 |
|
| 852 |
Completion will be reordered so that that the last ones are when |
| 853 |
possible from current session. |
| 854 |
|
| 855 |
Parameters |
| 856 |
---------- |
| 857 |
n : int |
| 858 |
The number of lines to get |
| 859 |
raw, output : bool |
| 860 |
See :meth:`get_range` |
| 861 |
include_latest : bool |
| 862 |
If False (default), n+1 lines are fetched, and the latest one |
| 863 |
is discarded. This is intended to be used where the function |
| 864 |
is called by a user command, which it should not return. |
| 865 |
|
| 866 |
Returns |
| 867 |
------- |
| 868 |
Tuples as :meth:`get_range` |
| 869 |
""" |
| 870 |
self.writeout_cache() |
| 871 |
if not include_latest: |
| 872 |
n += 1 |
| 873 |
# cursor/line/entry |
| 874 |
this_cur = list( |
| 875 |
self._run_sql( |
| 876 |
"WHERE session == ? ORDER BY line DESC LIMIT ? ", |
| 877 |
(self.session_number, n), |
| 878 |
raw=raw, |
| 879 |
output=output, |
| 880 |
) |
| 881 |
) |
| 882 |
other_cur = list( |
| 883 |
self._run_sql( |
| 884 |
"WHERE session != ? ORDER BY session DESC, line DESC LIMIT ?", |
| 885 |
(self.session_number, n), |
| 886 |
raw=raw, |
| 887 |
output=output, |
| 888 |
) |
| 889 |
) |
| 890 |
|
| 891 |
everything: list[tuple[int, int, InOrInOut]] = this_cur + other_cur |
| 892 |
|
| 893 |
everything = everything[:n] |
| 894 |
|
| 895 |
if not include_latest: |
| 896 |
return list(everything)[:0:-1] |
| 897 |
return list(everything)[::-1] |
| 898 |
|
| 899 |
def _get_range_session( |
| 900 |
self, |
| 901 |
start: int = 1, |
| 902 |
stop: Optional[int] = None, |
| 903 |
raw: bool = True, |
| 904 |
output: bool = False, |
| 905 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 906 |
"""Get input and output history from the current session. Called by |
| 907 |
get_range, and takes similar parameters.""" |
| 908 |
input_hist = self.input_hist_raw if raw else self.input_hist_parsed |
| 909 |
|
| 910 |
n = len(input_hist) |
| 911 |
if start < 0: |
| 912 |
start += n |
| 913 |
if not stop or (stop > n): |
| 914 |
stop = n |
| 915 |
elif stop < 0: |
| 916 |
stop += n |
| 917 |
line: InOrInOut |
| 918 |
for i in range(start, stop): |
| 919 |
if output: |
| 920 |
line = (input_hist[i], self.output_hist_reprs.get(i)) |
| 921 |
else: |
| 922 |
line = input_hist[i] |
| 923 |
yield (0, i, line) |
| 924 |
|
| 925 |
def get_range( |
| 926 |
self, |
| 927 |
session: int = 0, |
| 928 |
start: int = 1, |
| 929 |
stop: Optional[int] = None, |
| 930 |
raw: bool = True, |
| 931 |
output: bool = False, |
| 932 |
) -> Iterable[tuple[int, int, InOrInOut]]: |
| 933 |
"""Retrieve input by session. |
| 934 |
|
| 935 |
Parameters |
| 936 |
---------- |
| 937 |
session : int |
| 938 |
Session number to retrieve. The current session is 0, and negative |
| 939 |
numbers count back from current session, so -1 is previous session. |
| 940 |
start : int |
| 941 |
First line to retrieve. |
| 942 |
stop : int |
| 943 |
End of line range (excluded from output itself). If None, retrieve |
| 944 |
to the end of the session. |
| 945 |
raw : bool |
| 946 |
If True, return untranslated input |
| 947 |
output : bool |
| 948 |
If True, attempt to include output. This will be 'real' Python |
| 949 |
objects for the current session, or text reprs from previous |
| 950 |
sessions if db_log_output was enabled at the time. Where no output |
| 951 |
is found, None is used. |
| 952 |
|
| 953 |
Returns |
| 954 |
------- |
| 955 |
entries |
| 956 |
An iterator over the desired lines. Each line is a 3-tuple, either |
| 957 |
(session, line, input) if output is False, or |
| 958 |
(session, line, (input, output)) if output is True. |
| 959 |
""" |
| 960 |
if session <= 0: |
| 961 |
session += self.session_number |
| 962 |
if session == self.session_number: # Current session |
| 963 |
return self._get_range_session(start, stop, raw, output) |
| 964 |
return super(HistoryManager, self).get_range(session, start, stop, raw, output) |
| 965 |
|
| 966 |
## ---------------------------- |
| 967 |
## Methods for storing history: |
| 968 |
## ---------------------------- |
| 969 |
def store_inputs( |
| 970 |
self, line_num: int, source: str, source_raw: Optional[str] = None |
| 971 |
) -> None: |
| 972 |
"""Store source and raw input in history and create input cache |
| 973 |
variables ``_i*``. |
| 974 |
|
| 975 |
Parameters |
| 976 |
---------- |
| 977 |
line_num : int |
| 978 |
The prompt number of this input. |
| 979 |
source : str |
| 980 |
Python input. |
| 981 |
source_raw : str, optional |
| 982 |
If given, this is the raw input without any IPython transformations |
| 983 |
applied to it. If not given, ``source`` is used. |
| 984 |
""" |
| 985 |
if source_raw is None: |
| 986 |
source_raw = source |
| 987 |
source = source.rstrip("\n") |
| 988 |
source_raw = source_raw.rstrip("\n") |
| 989 |
|
| 990 |
# do not store exit/quit commands |
| 991 |
if self._exit_re.match(source_raw.strip()): |
| 992 |
return |
| 993 |
|
| 994 |
self.input_hist_parsed.append(source) |
| 995 |
self.input_hist_raw.append(source_raw) |
| 996 |
|
| 997 |
with self.db_input_cache_lock: |
| 998 |
self.db_input_cache.append((line_num, source, source_raw)) |
| 999 |
# Trigger to flush cache and write to DB. |
| 1000 |
if len(self.db_input_cache) >= self.db_cache_size: |
| 1001 |
if self.using_thread: |
| 1002 |
self._restart_thread_if_stopped() |
| 1003 |
if self.save_flag is not None: |
| 1004 |
self.save_flag.set() |
| 1005 |
|
| 1006 |
# update the auto _i variables |
| 1007 |
self._iii = self._ii |
| 1008 |
self._ii = self._i |
| 1009 |
self._i = self._i00 |
| 1010 |
self._i00 = source_raw |
| 1011 |
|
| 1012 |
# hackish access to user namespace to create _i1,_i2... dynamically |
| 1013 |
new_i = "_i%s" % line_num |
| 1014 |
to_main = {"_i": self._i, "_ii": self._ii, "_iii": self._iii, new_i: self._i00} |
| 1015 |
|
| 1016 |
if self.shell is not None: |
| 1017 |
self.shell.push(to_main, interactive=False) |
| 1018 |
|
| 1019 |
def store_output(self, line_num: int) -> None: |
| 1020 |
"""If database output logging is enabled, this saves all the |
| 1021 |
outputs from the indicated prompt number to the database. It's |
| 1022 |
called by run_cell after code has been executed. |
| 1023 |
|
| 1024 |
Parameters |
| 1025 |
---------- |
| 1026 |
line_num : int |
| 1027 |
The line number from which to save outputs |
| 1028 |
""" |
| 1029 |
if (not self.db_log_output) or (line_num not in self.output_hist_reprs): |
| 1030 |
return |
| 1031 |
lnum: int = line_num |
| 1032 |
output = self.output_hist_reprs[line_num] |
| 1033 |
|
| 1034 |
with self.db_output_cache_lock: |
| 1035 |
self.db_output_cache.append((line_num, output)) |
| 1036 |
if self.db_cache_size <= 1 and self.using_thread: |
| 1037 |
self._restart_thread_if_stopped() |
| 1038 |
if self.save_flag is not None: |
| 1039 |
self.save_flag.set() |
| 1040 |
|
| 1041 |
def _writeout_input_cache(self, conn: sqlite3.Connection) -> None: |
| 1042 |
with conn: |
| 1043 |
for line in self.db_input_cache: |
| 1044 |
conn.execute( |
| 1045 |
"INSERT INTO history VALUES (?, ?, ?, ?)", |
| 1046 |
(self.session_number,) + line, |
| 1047 |
) |
| 1048 |
|
| 1049 |
def _writeout_output_cache(self, conn: sqlite3.Connection) -> None: |
| 1050 |
with conn: |
| 1051 |
for line in self.db_output_cache: |
| 1052 |
conn.execute( |
| 1053 |
"INSERT INTO output_history VALUES (?, ?, ?)", |
| 1054 |
(self.session_number,) + line, |
| 1055 |
) |
| 1056 |
|
| 1057 |
@only_when_enabled |
| 1058 |
def writeout_cache(self, conn: Optional[sqlite3.Connection] = None) -> None: |
| 1059 |
"""Write any entries in the cache to the database.""" |
| 1060 |
if conn is None: |
| 1061 |
conn = self.db |
| 1062 |
|
| 1063 |
with self.db_input_cache_lock: |
| 1064 |
try: |
| 1065 |
self._writeout_input_cache(conn) |
| 1066 |
except sqlite3.IntegrityError: |
| 1067 |
self.new_session(conn) |
| 1068 |
print( |
| 1069 |
"ERROR! Session/line number was not unique in", |
| 1070 |
"database. History logging moved to new session", |
| 1071 |
self.session_number, |
| 1072 |
) |
| 1073 |
try: |
| 1074 |
# Try writing to the new session. If this fails, don't |
| 1075 |
# recurse |
| 1076 |
self._writeout_input_cache(conn) |
| 1077 |
except sqlite3.IntegrityError: |
| 1078 |
pass |
| 1079 |
finally: |
| 1080 |
self.db_input_cache = [] |
| 1081 |
|
| 1082 |
with self.db_output_cache_lock: |
| 1083 |
try: |
| 1084 |
self._writeout_output_cache(conn) |
| 1085 |
except sqlite3.IntegrityError: |
| 1086 |
print( |
| 1087 |
"!! Session/line number for output was not unique", |
| 1088 |
"in database. Output will not be stored.", |
| 1089 |
) |
| 1090 |
finally: |
| 1091 |
self.db_output_cache = [] |
| 1092 |
|
| 1093 |
|
| 1094 |
if hasattr(os, "register_at_fork"): |
| 1095 |
os.register_at_fork(before=HistoryManager._stop_thread) |
| 1096 |
|
| 1097 |
|
| 1098 |
from collections.abc import Callable, Iterator |
| 1099 |
from weakref import ReferenceType |
| 1100 |
|
| 1101 |
|
| 1102 |
@contextmanager |
| 1103 |
def hold(ref: ReferenceType[HistoryManager]) -> Iterator[ReferenceType[HistoryManager]]: |
| 1104 |
""" |
| 1105 |
Context manger that hold a reference to a weak ref to make sure it |
| 1106 |
is not GC'd during it's context. |
| 1107 |
""" |
| 1108 |
r = ref() |
| 1109 |
yield ref |
| 1110 |
del r |
| 1111 |
|
| 1112 |
|
| 1113 |
class HistorySavingThread(threading.Thread): |
| 1114 |
"""This thread takes care of writing history to the database, so that |
| 1115 |
the UI isn't held up while that happens. |
| 1116 |
|
| 1117 |
It waits for the HistoryManager's save_flag to be set, then writes out |
| 1118 |
the history cache. The main thread is responsible for setting the flag when |
| 1119 |
the cache size reaches a defined threshold.""" |
| 1120 |
|
| 1121 |
save_flag: threading.Event |
| 1122 |
daemon: bool = True |
| 1123 |
_stop_now: bool = False |
| 1124 |
enabled: bool = True |
| 1125 |
history_manager: ref[HistoryManager] |
| 1126 |
_stopped = False |
| 1127 |
|
| 1128 |
def __init__(self, history_manager: HistoryManager) -> None: |
| 1129 |
super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread") |
| 1130 |
self.history_manager = ref(history_manager) |
| 1131 |
self.enabled = history_manager.enabled |
| 1132 |
self.save_flag = threading.Event() |
| 1133 |
|
| 1134 |
@only_when_enabled |
| 1135 |
def run(self) -> None: |
| 1136 |
atexit.register(self.stop) |
| 1137 |
# We need a separate db connection per thread: |
| 1138 |
try: |
| 1139 |
hm: ReferenceType[HistoryManager] |
| 1140 |
with hold(self.history_manager) as hm: |
| 1141 |
if hm() is not None: |
| 1142 |
self.db = sqlite3.connect( |
| 1143 |
str(hm().hist_file), # type: ignore [union-attr] |
| 1144 |
**cast(dict[str, t.Any], hm().connection_options), # type: ignore [union-attr] |
| 1145 |
) |
| 1146 |
while True: |
| 1147 |
self.save_flag.wait() |
| 1148 |
with hold(self.history_manager) as hm: |
| 1149 |
if hm() is None: |
| 1150 |
self._stop_now = True |
| 1151 |
if self._stop_now: |
| 1152 |
self.db.close() |
| 1153 |
return |
| 1154 |
self.save_flag.clear() |
| 1155 |
if hm() is not None: |
| 1156 |
hm().writeout_cache(self.db) # type: ignore [union-attr] |
| 1157 |
|
| 1158 |
except Exception as e: |
| 1159 |
print( |
| 1160 |
( |
| 1161 |
"The history saving thread hit an unexpected error (%s)." |
| 1162 |
"History will not be written to the database." |
| 1163 |
) |
| 1164 |
% repr(e) |
| 1165 |
) |
| 1166 |
finally: |
| 1167 |
atexit.unregister(self.stop) |
| 1168 |
|
| 1169 |
def stop(self) -> None: |
| 1170 |
"""This can be called from the main thread to safely stop this thread. |
| 1171 |
|
| 1172 |
Note that it does not attempt to write out remaining history before |
| 1173 |
exiting. That should be done by calling the HistoryManager's |
| 1174 |
end_session method.""" |
| 1175 |
if self._stopped: |
| 1176 |
return |
| 1177 |
self._stop_now = True |
| 1178 |
|
| 1179 |
self.save_flag.set() |
| 1180 |
self._stopped = True |
| 1181 |
if self != threading.current_thread(): |
| 1182 |
self.join() |
| 1183 |
|
| 1184 |
def __del__(self) -> None: |
| 1185 |
self.stop() |
| 1186 |
|
| 1187 |
|
| 1188 |
# To match, e.g. ~5/8-~2/3, or ~4 (without trailing slash for full session) |
| 1189 |
# Session numbers: ~N or N/ |
| 1190 |
# Line numbers: N (just digits, no ~) |
| 1191 |
# Range syntax: 4-6 (with end) or 4- (without end, means "onward") |
| 1192 |
range_re = re.compile( |
| 1193 |
r""" |
| 1194 |
((?P<startsess>(?:~?\d+/)))? |
| 1195 |
(?P<start>\d+)? |
| 1196 |
((?P<sep>[\-:]) |
| 1197 |
((?P<endsess>(?:~?\d+/)))? |
| 1198 |
(?P<end>\d*))? |
| 1199 |
$""", |
| 1200 |
re.VERBOSE, |
| 1201 |
) |
| 1202 |
|
| 1203 |
|
| 1204 |
def extract_hist_ranges(ranges_str: str) -> Iterable[tuple[int, int, Optional[int]]]: |
| 1205 |
"""Turn a string of history ranges into 3-tuples of (session, start, stop). |
| 1206 |
|
| 1207 |
Empty string results in a `[(0, 1, None)]`, i.e. "everything from current |
| 1208 |
session". |
| 1209 |
|
| 1210 |
Examples |
| 1211 |
-------- |
| 1212 |
>>> list(extract_hist_ranges("~8/5-~7/4 2")) |
| 1213 |
[(-8, 5, None), (-7, 1, 5), (0, 2, 3)] |
| 1214 |
>>> list(extract_hist_ranges("~4/")) |
| 1215 |
[(-4, 1, None)] |
| 1216 |
>>> list(extract_hist_ranges("4-")) |
| 1217 |
[(0, 4, None)] |
| 1218 |
>>> list(extract_hist_ranges("~4/4-")) |
| 1219 |
[(-4, 4, None)] |
| 1220 |
""" |
| 1221 |
if ranges_str == "": |
| 1222 |
yield (0, 1, None) # Everything from current session |
| 1223 |
return |
| 1224 |
|
| 1225 |
for range_str in ranges_str.split(): |
| 1226 |
rmatch = range_re.match(range_str) |
| 1227 |
if not rmatch: |
| 1228 |
continue |
| 1229 |
start = rmatch.group("start") |
| 1230 |
sep = rmatch.group("sep") |
| 1231 |
if start: |
| 1232 |
start = int(start) |
| 1233 |
end = rmatch.group("end") |
| 1234 |
if sep == "-": |
| 1235 |
end = (int(end) + 1) if end else None |
| 1236 |
else: |
| 1237 |
end = int(end) if end else start + 1 |
| 1238 |
else: |
| 1239 |
if not rmatch.group("startsess"): |
| 1240 |
continue |
| 1241 |
start = 1 |
| 1242 |
end = None |
| 1243 |
startsess = rmatch.group("startsess") or "0" |
| 1244 |
endsess = rmatch.group("endsess") or startsess |
| 1245 |
startsess = startsess.rstrip("/") |
| 1246 |
endsess = endsess.rstrip("/") |
| 1247 |
startsess = int(startsess.replace("~", "-")) |
| 1248 |
endsess = int(endsess.replace("~", "-")) |
| 1249 |
assert endsess >= startsess, "start session must be earlier than end session" |
| 1250 |
|
| 1251 |
if endsess == startsess: |
| 1252 |
yield (startsess, start, end) |
| 1253 |
continue |
| 1254 |
# Multiple sessions in one range: |
| 1255 |
yield (startsess, start, None) |
| 1256 |
for sess in range(startsess + 1, endsess): |
| 1257 |
yield (sess, 1, None) |
| 1258 |
yield (endsess, 1, end) |
| 1259 |
|
| 1260 |
|
| 1261 |
def _format_lineno(session: int, line: int) -> str: |
| 1262 |
"""Helper function to format line numbers properly.""" |
| 1263 |
if session == 0: |
| 1264 |
return str(line) |
| 1265 |
return "%s#%s" % (session, line) |