Files
Vlad Lasky a6c67f8cb2 history.py: keep every line and byte of the file when adding a row
An earlier commit on this branch made a corrupt history readable by
decoding with errors="replace" and skipping lines that are not JSON
objects. But add() rewrote the file from the rows it had parsed, so the
next add destroyed whatever it could not read, where upstream crashed
and left the file alone:

- Windows PowerShell 5 writes UTF-16 LE by default (`$rows | Out-File`).
  The whole file failed to parse, `moves.py` said "no moves saved yet",
  and the next add left a file with only the new row, with no warning.
- A cp1252 file from `Set-Content` ("Łódź" saved as ANSI) was listed as
  "L�dz", and the next add wrote U+FFFD into the file for good.
- Any line that was not a JSON object was dropped at the next add.

Now:
- A file that starts with a UTF-16 BOM (FF FE or FE FF) is decoded as
  UTF-16, and the next add writes it back as UTF-8.
- Anything else is decoded as UTF-8 with errors="surrogateescape" and
  written back the same way, so bytes that are not UTF-8 survive byte
  for byte. The listing shows them as "?", since stdout already uses
  errors="replace".
- add() keeps the existing lines as text and appends the new row,
  instead of re-serialising parsed rows. Lines that are not JSON objects
  stay in the file. They count toward the 300-row cap and are trimmed
  oldest first like the rest. Blank lines are dropped, and a "\r" at the
  end of a line is removed, so a CRLF file comes back with one line
  ending per row.
- load() still returns only the lines that parse as JSON objects.

On Linux: the bytes of a cp1252 file were unchanged after an add, UTF-16
LE and BE files with CRLF kept all 3 rows and became UTF-8, junk lines
("not json at all", 5, null) were still there after an add, and a
300-line file with a junk first line dropped exactly that line when one
row was added.
2026-11-26 14:56:06 +11:00

139 lines
3.5 KiB
Python

import json
import os
import shutil
import sys
import time
def state_dir():
xdg = os.environ.get("XDG_STATE_HOME", "")
if os.path.isabs(xdg):
return xdg
return os.path.join(os.path.expanduser("~"), ".local", "state")
def history_path():
custom = os.environ.get("ANTIALGORITHM_HISTORY")
if not custom:
return os.path.join(state_dir(), "antialgorithm", "history.jsonl")
custom = os.path.abspath(os.path.expanduser(custom))
if os.path.isdir(custom):
return os.path.join(custom, "history.jsonl")
return custom
PATH = history_path()
OLD_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "history.jsonl")
LIMIT = 300
LOCK_WAIT = 15
LOCK_STALE = 10
def acquire(lock):
deadline = time.monotonic() + LOCK_WAIT
while time.monotonic() < deadline:
try:
os.close(os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
return
except FileExistsError:
pass
except PermissionError:
if os.name != "nt":
raise
try:
if time.time() - os.path.getmtime(lock) > LOCK_STALE:
os.remove(lock)
continue
except (FileNotFoundError, PermissionError):
pass
time.sleep(0.02)
raise TimeoutError(f"could not create the lock file {lock} within {LOCK_WAIT} s")
def release(lock):
try:
os.remove(lock)
except FileNotFoundError:
pass
def retry_denied(action):
for attempt in range(50):
try:
return action()
except PermissionError:
if attempt == 49:
raise
time.sleep(0.02)
def read_text():
with open(PATH, "rb") as f:
data = f.read()
if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
return data.decode("utf-16", errors="replace")
return data.decode("utf-8-sig", errors="surrogateescape")
def migrate():
if os.path.exists(PATH) or not os.path.exists(OLD_PATH):
return
os.makedirs(os.path.dirname(PATH), exist_ok=True)
lock = PATH + ".lock"
acquire(lock)
try:
if not os.path.exists(PATH):
shutil.copyfile(OLD_PATH, PATH)
finally:
release(lock)
def read_lines():
try:
text = retry_denied(read_text)
except FileNotFoundError:
return []
return [line.rstrip("\r") for line in text.split("\n") if line.strip()]
def read():
out = []
for line in read_lines():
try:
entry = json.loads(line)
except ValueError:
continue
if isinstance(entry, dict):
out.append(entry)
return out
def load(kind=None):
try:
migrate()
rows = read()
except OSError as e:
print(f"could not read the history: {e}", file=sys.stderr)
return []
return [row for row in rows if kind is None or row.get("type") == kind]
def add(entry):
entry = {"date": time.strftime("%Y-%m-%d"), **entry}
migrate()
os.makedirs(os.path.dirname(PATH), exist_ok=True)
lock = PATH + ".lock"
acquire(lock)
try:
lines = read_lines()[-(LIMIT - 1):] + [json.dumps(entry, ensure_ascii=False)]
tmp = f"{PATH}.{os.getpid()}.tmp"
try:
with open(tmp, "w", encoding="utf-8", errors="surrogateescape") as f:
f.writelines(line + "\n" for line in lines)
retry_denied(lambda: os.replace(tmp, PATH))
finally:
if os.path.exists(tmp):
os.remove(tmp)
finally:
release(lock)