Skip to content
Merged
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
33 changes: 33 additions & 0 deletions tests/test_story_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,39 @@ def failing_dump(obj, f, **kwargs):
self.assertEqual(f.read(), prior)
self.assertEqual(sorted(os.listdir(self.root)), before)

def test_failed_replace_of_read_only_report_makes_stage_deletable(self):
"""A failed replace over a read-only report still cleans the stage: the staged file has the
read-only destination's bits, so the cleanup makes it deletable before deleting, and one
delete failure is swallowed instead of masking the replace error (Windows behavior)."""
out = os.path.join(self.root, "out.json")
with open(out, "w", encoding="utf-8") as f:
f.write('{"prior": true}')
with open(out, "rb") as f:
prior = f.read()
os.chmod(out, 0o444)
self.addCleanup(lambda: os.path.exists(out) and os.chmod(out, 0o600))
made_writable = []
real_chmod = os.chmod

def chmod(staged_path, mode, *args, **kwargs):
if isinstance(staged_path, str) and os.path.basename(staged_path).startswith("story_index") \
and mode == 0o600:
made_writable.append(staged_path)
return real_chmod(staged_path, mode, *args, **kwargs)

with self.assertRaises(OSError) as raised:
with mock.patch.object(story_index.os, "replace", side_effect=OSError("replace denied")), \
mock.patch.object(story_index.os, "chmod", chmod):
story_index.write_output(out, [{"offset": 0x100, "stored": 8, "size": 9,
"signature": "psin", "version": None, "count": 1,
"detail": ""}], {"files": 1})
self.assertIn("replace denied", str(raised.exception))
self.assertEqual(len(made_writable), 1) # the stage was made deletable
with open(out, "rb") as f:
self.assertEqual(f.read(), prior) # the prior report is untouched
self.assertEqual([n for n in os.listdir(self.root) if n.startswith("story_index")], [])
self.assertNotIn(".tmp", " ".join(os.listdir(self.root))) # no staging directory stranded

def test_cli(self):
out = os.path.join(self.root, "cli.json")
p = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--quiet"],
Expand Down
17 changes: 14 additions & 3 deletions tools/story_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import tempfile
import time
import zlib
from contextlib import suppress

# -I keeps the script directory off sys.path; add it back so the sibling helpers are importable.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
Expand Down Expand Up @@ -296,16 +297,19 @@ def write_output(path, rows, summary):

The stage lives in a private TemporaryDirectory under the destination's parent, so os.replace
only ever renames within one filesystem. A late failure closes the stage and leaves any prior
report byte-for-byte intact. The destination is resolved first, so a report path that is a
report byte-for-byte intact; the staged file is made deletable first, so a read-only report on
Windows cannot strand the stage or mask the error with a cleanup failure. The destination is
resolved first, so a report path that is a
symlink is published through to its target the way open(..., "w") did before. Because os.replace
unlinks the previous report file only at the destination name, other hard links to it keep the
previous contents.
"""
ext = os.path.splitext(path)[1].lower()
dest = os.path.realpath(path)
parent = os.path.dirname(dest)
with tempfile.TemporaryDirectory(dir=parent) as staging:
staged = os.path.join(staging, "story_index" + ext)
stage_dir = tempfile.TemporaryDirectory(dir=parent)
try:
staged = os.path.join(stage_dir.name, "story_index" + ext)
if ext == ".json":
with open(staged, "w", encoding="utf-8", newline="\n") as f:
json.dump({"summary": summary, "files": rows}, f, indent=1)
Expand All @@ -320,6 +324,13 @@ def write_output(path, rows, summary):
# (an existing report's, or what open() would have made for a new file) so perms are stable.
os.chmod(staged, published_mode(dest))
os.replace(staged, dest)
finally:
# On a failed replace the staged file carries the destination's bits, which a read-only report
# makes read-only: Windows then refuses the delete and the cleanup error masks the real one.
# Make it deletable first and let one delete failure go, so the caller reports the replace.
with suppress(OSError):
os.chmod(staged, 0o600)
stage_dir.cleanup()


def byte_count(text):
Expand Down