fix: publish new Windows outputs without requiring hard links

This commit is contained in:
2026-11-05 12:15:12 +08:00
parent 36f0d7856e
commit 17e55cb7bd
2 changed files with 19 additions and 5 deletions
+6 -2
View File
@@ -14,7 +14,9 @@ _UNCHECKED = object()
def fingerprint(path: Path):
try:
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
digest = hashlib.sha256()
for block in iter(lambda: stream.read(1024 * 1024), b''): digest.update(block)
return digest.hexdigest()
except FileNotFoundError:
return None
@@ -42,7 +44,9 @@ def _checked_replace(temporary: Path, path: Path, expected: str | None) -> None:
raise OSError(f'文件发生变化,已停止替换:{path}')
if expected is None:
# Creating the directory entry must fail if another process got there first.
os.link(temporary, path)
# Windows rename is exclusive and also works on volumes without hardlinks.
if os.name == 'nt': os.rename(temporary, path)
else: os.link(temporary, path)
return
backup = _recovery_path(path)
try:
+13 -3
View File
@@ -44,15 +44,25 @@ def test_transactions_retain_external_save_at_commit(tmp_path, monkeypatch, oper
def test_creation_does_not_overwrite_file_created_at_commit(tmp_path, monkeypatch):
path = tmp_path/'new.out'
link = files.os.link
operation = 'rename' if files.os.name == 'nt' else 'link'
publish = getattr(files.os, operation)
def race(src, dst):
path.write_bytes(b'External creation')
link(src, dst)
monkeypatch.setattr(files.os, 'link', race)
publish(src, dst)
monkeypatch.setattr(files.os, operation, race)
with pytest.raises(FileExistsError): files.atomic_write(path, b'Export', expected=None)
assert path.read_bytes() == b'External creation'
@pytest.mark.skipif(files.os.name != 'nt', reason='Windows exclusive rename')
def test_new_output_does_not_require_hardlinks(tmp_path, monkeypatch):
def unsupported(*args): raise OSError('Hard links are not supported on this volume')
monkeypatch.setattr(files.os, 'link', unsupported)
path=tmp_path/'new.out'
files.atomic_write(path,b'Exported',expected=None)
assert path.read_bytes()==b'Exported'
def test_second_conflict_during_recovery_keeps_both_external_versions(tmp_path, monkeypatch):
path = tmp_path/'existing.out'; path.write_bytes(b'Original')
expected = files.fingerprint(path)