Skip to content

Commit e4c8abe

Browse files
committed
prompt-toolkit history now properly working with a persistent history file
1 parent 0a08c69 commit e4c8abe

File tree

3 files changed

+20
-10
lines changed

3 files changed

+20
-10
lines changed

cmd2/cmd2.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,11 @@ def __init__(
413413
# Commands to exclude from the help menu and tab completion
414414
self.hidden_commands = ['eof', '_relative_run_script']
415415

416+
# Initialize history from a persistent history file (if present)
417+
self.persistent_history_file = ''
418+
self._persistent_history_length = persistent_history_length
419+
self._initialize_history(persistent_history_file)
420+
416421
# Initialize prompt-toolkit PromptSession
417422
self.history_adapter = Cmd2History(self)
418423
self.completer = Cmd2Completer(self)
@@ -421,11 +426,6 @@ def __init__(
421426
completer=self.completer,
422427
)
423428

424-
# Initialize history from a persistent history file (if present)
425-
self.persistent_history_file = ''
426-
self._persistent_history_length = persistent_history_length
427-
self._initialize_history(persistent_history_file)
428-
429429
# Commands to exclude from the history command
430430
self.exclude_from_history = ['eof', 'history']
431431

cmd2/pt_utils.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,18 @@ def __init__(self, cmd_app: 'Cmd') -> None:
8484

8585
def load_history_strings(self) -> Iterable[str]:
8686
"""Yield strings from cmd2's history to prompt_toolkit."""
87-
for item in self.cmd_app.history:
88-
yield item.statement.raw
87+
last_item = None
88+
for item in reversed(self.cmd_app.history):
89+
if item.statement.raw != last_item:
90+
yield item.statement.raw
91+
last_item = item.statement.raw
92+
93+
def get_strings(self) -> list[str]:
94+
"""Get the strings from the history that are loaded so far."""
95+
if not self._loaded:
96+
self._loaded_strings = list(self.load_history_strings())
97+
self._loaded = True
98+
return super().get_strings()
8999

90100
def store_string(self, string: str) -> None:
91101
"""prompt_toolkit calls this when a line is accepted.

tests/test_history.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -978,9 +978,9 @@ def test_history_populates_pt(hist_file) -> None:
978978
# using the same rules
979979
pt_history = app.session.history.get_strings()
980980
assert len(pt_history) == 3
981-
assert pt_history.get(1) == 'help'
982-
assert pt_history.get(2) == 'shortcuts'
983-
assert pt_history.get(3) == 'alias'
981+
assert pt_history[0] == 'help'
982+
assert pt_history[1] == 'shortcuts'
983+
assert pt_history[2] == 'alias'
984984

985985

986986
#

0 commit comments

Comments
 (0)