Answer stability round 1: 0 🔴, 17 🟡 (0 misread); read line ends as before, drop a stale copy, say why a read failed, and test each failure the round named
This commit is contained in:
@@ -44,18 +44,19 @@ class FileStore:
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
try:
|
||||
# Decoded from bytes, so the text keeps the line ends the file holds.
|
||||
return self.path.read_bytes().decode("utf-8")
|
||||
return self.path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return ""
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"cannot read {self.path}: {failure}")
|
||||
except UnicodeDecodeError as failure:
|
||||
return Failure(f"cannot read {self.path}: not UTF-8 on line {failure.object[: failure.start].count(b'\n') + 1}")
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot read {self.path}: {failure.strerror}")
|
||||
|
||||
def write(self, text: str) -> Failure | None:
|
||||
try:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot write {self.path}: {failure}")
|
||||
return Failure(f"cannot write {self.path}: {failure.strerror}")
|
||||
unwritten = replace_file(self.path, text.encode("utf-8"))
|
||||
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
@@ -79,8 +80,13 @@ def local_file(record: RecordStore, copy: pathlib.Path) -> pathlib.Path | Failur
|
||||
text = record.read()
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
if text and (unwritten := FileStore(copy, None).write(text)):
|
||||
return unwritten
|
||||
if text:
|
||||
return FileStore(copy, None).write(text) or copy
|
||||
try:
|
||||
# An earlier copy would read as the record's text, and `stored` would put it back.
|
||||
copy.unlink(missing_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot remove {copy}: {failure.strerror}")
|
||||
return copy
|
||||
|
||||
|
||||
@@ -91,4 +97,4 @@ def stored(record: RecordStore, copy: pathlib.Path) -> Failure | None:
|
||||
text = FileStore(copy, None).read()
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
return record.write(text) if text else Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}; `record open` writes the file to edit")
|
||||
return record.write(text) if text else Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}")
|
||||
|
||||
Reference in New Issue
Block a user