Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/prompt_toolkit/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,14 @@ def add() -> None:
return reversed(strings)

def store_string(self, string: str) -> None:
# Save to file.
with open(self.filename, "ab") as f:
# Save to file. The history can contain anything the user typed, so
# create the file readable by the owner only (like readline does).
fd = os.open(
self.filename,
os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0),
0o600,
)
with open(fd, "ab") as f:

def write(t: str) -> None:
f.write(t.encode("utf-8", errors="replace"))
Expand Down
17 changes: 17 additions & 0 deletions tests/test_history.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from __future__ import annotations

import os
import stat
import sys
from asyncio import run

import pytest

from prompt_toolkit.history import FileHistory, InMemoryHistory, ThreadedHistory


Expand Down Expand Up @@ -60,6 +65,18 @@ def test_file_history(tmpdir):
assert _call_history_load(history2) == ["test3", "world", "hello"]


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX file modes")
def test_file_history_permissions(tmpdir):
histfile = tmpdir.join("history")
old_umask = os.umask(0o022)
try:
FileHistory(histfile).append_string("hello")
finally:
os.umask(old_umask)

assert stat.S_IMODE(os.stat(histfile).st_mode) == 0o600


def test_threaded_file_history(tmpdir):
histfile = tmpdir.join("history")

Expand Down
Loading