diff --git a/design/file-helper.md b/design/file-helper.md index b9fca560b7..9244ca8bc5 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -250,6 +250,17 @@ descriptor-relative or change their documented concurrency limitations. with cleanup details attached as a note. The yielded path uses the same spelling rule as `iterdir`; cleanup uses the resolved staging location. - `read_bytes(path)` / `read_text(path, encoding="utf-8")` read regular files. +- `stat(path)` returns the metadata of an existing entry after the normal policy + walk: allowed contained links, including a leaf link, are resolved, and the + resolved entry itself is not followed. On POSIX the entry is queried relative + to the anchored parent hierarchy, so a parent swapped after resolution cannot + redirect it. On Windows the parent hierarchy is pinned but the leaf is still + queried by absolute pathname, so that protection does not apply there (see + Safety limits and migration). The root itself is queried without following a + link, so a root replaced by a link after construction is not followed. + Missing entries raise `FileNotFoundError`. It is a + point-in-time query, not an anchor: callers that act on the result must + re-check identity on the descriptor they act through. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. @@ -312,6 +323,29 @@ descriptor-relative or change their documented concurrency limitations. Windows creation also honors the CRT process mask: masking the owner-write bit creates a read-only file, matching native text creation, without changing the attributes of an existing file. +- `open_rewrite(path)` is a context manager yielding a blocking, binary, + writable descriptor on an existing regular file at offset 0, for in-place byte + rewrites that must keep the file's identity, owner, permission bits, ACL and + hard links. POSIX may clear the set-user-ID and set-group-ID bits when the + caller writes or truncates through it, as for any unprivileged write; the + helper keeps that OS behaviour and does not restore them. It uses + `overwrite_text`'s anchored, non-truncating open, but never creates: POSIX + omits `O_CREAT` and Windows does not fall back to creation, so a leaf + removed after resolution raises `FileNotFoundError`. The opened file type is + checked with `fstat` before the descriptor is yielded. The helper closes the + descriptor on exit, so callers must not close it; wrap it with + `closefd=False`. Writing, truncating, flushing and any rollback belong to the + caller; nothing is written or truncated by the helper. There is no newline + translation on either platform. +- `rewrite_descriptor(fd, content)` (static) replaces the whole content of a + descriptor returned by `open_rewrite`: it seeks to offset 0, writes every + byte (retrying short writes), truncates to the new length after writing, then + `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. An + append-mode descriptor is refused (`EINVAL`) before anything is written, + since its writes ignore the seek and the truncate would cut them off. Like + any write, it may clear the set-user-ID and set-group-ID bits on POSIX, and + they are not restored. A failure can leave partial content; restoring it is + the caller's job. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. Recursive enumeration and each removal use anchored @@ -447,10 +481,10 @@ its replacement: creation stays with the opened directory, even if it is renamed out of the root. This is not a guarantee of stable namespace membership under concurrent renames, nor does parent anchoring make every leaf preflight atomic with the subsequent open. -On Windows, exclusive creation and text overwrite still open their leaf by -pathname after pinning the parent hierarchy. Attribute-only reparse updates -can redirect those opens; they do not have the read path's parent-relative -handle protection. +On Windows, exclusive creation, text overwrite and `open_rewrite` still open +their leaf by pathname after pinning the parent hierarchy, and `stat` queries +its leaf the same way. Attribute-only reparse updates can redirect those +opens; they do not have the read path's parent-relative handle protection. The helper does not constrain subprocesses or third-party code. Existing safe-write mechanisms informed this helper, but existing shared diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 9dceb5a80e..cbf6cbd50b 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -462,11 +462,13 @@ def windows_read_fd(handle: int) -> Iterator[int]: @contextmanager -def _windows_overwrite_fd(path: Path) -> Iterator[int]: +def _windows_overwrite_fd(path: Path, *, create: bool = True) -> Iterator[int]: """Open/create without following a new leaf or changing the CRT mask.""" try: handle = _open_windows_handle(path, directory=False, overwrite=True) except FileNotFoundError: + if not create: + raise attributes = _windows_creation_attributes() handle = _open_windows_handle( path, directory=False, overwrite=True, create_attributes=attributes diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 9b00895ae0..dbe4935705 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -33,6 +33,29 @@ _POSIX_OPEN = os.open +def _full_fsync(fd: int) -> None: + """Flush to stable storage; macOS ``fsync`` alone leaves data in the drive cache.""" + os.fsync(fd) + if sys.platform == "darwin": + import fcntl + + try: + fcntl.fcntl(fd, fcntl.F_FULLFSYNC) + except OSError as error: + # Not every filesystem supports it, and fsync has already run. + if error.errno not in (errno.ENOTSUP, errno.EOPNOTSUPP, errno.EINVAL, errno.ENOTTY): + raise + + +def _write_all(fd: int, content: bytes) -> None: + view = memoryview(content) + while view: + count = os.write(fd, view) + if count == 0: + raise OSError(errno.EIO, "Write made no progress") + view = view[count:] + + def _strip_extended_length_prefix(path: _PathType) -> _PathType: """Normalize Windows extended drive/UNC spellings for comparison only.""" raw = str(path) @@ -381,6 +404,35 @@ def _require_directory(path: Path) -> None: if not stat.S_ISDIR(path.stat().st_mode): raise NotADirectoryError(path) + def stat(self, path: Path | str) -> os.stat_result: + """Return the metadata of an existing entry, resolving only allowed links. + + On POSIX the leaf is queried relative to the anchored parent, so a + parent swapped after resolution cannot redirect it. On Windows the + parent hierarchy is pinned but the leaf is queried by absolute + pathname, so that protection does not apply there. + """ + destination = self._path(path) + if destination == self._canonical_root: + return os.stat(destination, follow_symlinks=False) + # Pin the parent hierarchy; only the POSIX path below queries the leaf through it. + if os.name == "nt": + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + parent = stack.enter_context(_windows_handle( + self._canonical_root, directory=True, traverse=True, + )) + for part in parts[:-1]: + parent = stack.enter_context(_windows_handle( + Path(part), directory=True, parent=parent, traverse=True, + )) + return os.stat(destination, follow_symlinks=False) + unsupported = "Anchored stat is unsupported on this platform" + if os.stat not in os.supports_dir_fd or os.stat not in os.supports_follow_symlinks: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: + return os.stat(destination.name, dir_fd=directory, follow_symlinks=False) + def directory_exists(self, path: Path | str) -> bool: """Return False for absence only; reject wrong types and forbidden paths.""" try: @@ -620,7 +672,52 @@ def overwrite_text( stream.write(content) @contextmanager - def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: + def open_rewrite(self, path: Path | str) -> Iterator[int]: + """Yield a blocking binary write descriptor on an existing regular file, untruncated. + + The descriptor starts at offset 0 and the helper closes it on exit, so the + caller must not close it (wrap it with ``os.fdopen(fd, "wb", closefd=False)``). + The caller owns writing, truncating and flushing; owner, permission bits + and links are unchanged. On POSIX, the caller's write or truncate may clear + the set-user-ID and set-group-ID bits, as any unprivileged write does; the + helper keeps that behaviour and does not restore them. + """ + destination = self._path(path) + self._require_file(destination) + with self._overwrite_descriptor(destination, create=False) as fd: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise UnsupportedPathError(f"Expected a regular file: {destination}") + if os.name != "nt": + # Opened non-blocking only so a FIFO swapped in cannot hang the open. + os.set_blocking(fd, True) + yield fd + + @staticmethod + def rewrite_descriptor(fd: int, content: bytes) -> None: + """Replace everything in the open file ``fd`` with ``content``, flushed to disk. + + Only for a descriptor from ``open_rewrite``. It writes from offset 0 + whatever the current offset, truncates after writing (so the old bytes' + space is reused rather than freed first), then ``fsync``s, adding + ``F_FULLFSYNC`` on macOS where the filesystem supports it. An append-mode + descriptor is refused before anything is written, since its writes + ignore the seek and the truncate would then cut them off. On POSIX the + write may clear the set-user-ID and set-group-ID bits; they are not + restored. A failure can leave partial content; restoring it is the + caller's job. + """ + if os.name != "nt": + import fcntl + + if fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_APPEND: + raise OSError(errno.EINVAL, "Refusing to rewrite through an append-mode descriptor") + os.lseek(fd, 0, os.SEEK_SET) + _write_all(fd, content) + os.ftruncate(fd, len(content)) + _full_fsync(fd) + + @contextmanager + def _overwrite_descriptor(self, destination: Path, *, create: bool = True) -> Iterator[int]: """Anchor the resolved hierarchy before opening a non-truncating leaf.""" with ExitStack() as stack: if os.name == "nt": @@ -630,7 +727,7 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: for part in parts[:-1]: current = current / part stack.enter_context(_windows_handle(current, directory=True)) - yield stack.enter_context(_windows_overwrite_fd(destination)) + yield stack.enter_context(_windows_overwrite_fd(destination, create=create)) return unsupported = "Scoped text overwrite is unsupported on this platform" @@ -638,8 +735,8 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: raise OSError(errno.ENOTSUP, unsupported) with self._posix_directory(destination.parent, unsupported_message=unsupported) as parent: flags = ( - os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK - | getattr(os, "O_CLOEXEC", 0) + os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0) + | (os.O_CREAT if create else 0) ) fd = os.open(destination.name, flags, 0o666, dir_fd=parent) try: diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 1448be9121..b150a8f163 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -776,7 +776,8 @@ def denied(*args, **kwargs): raise PermissionError("denied") if os.name == "nt": - def denied_windows(path): + def denied_windows(path, *, create=True): + assert create assert path == root / "new" calls.append(path) raise PermissionError("denied") diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 2a785a32d5..6dfb6f9a24 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -540,7 +540,8 @@ def pin(path, *, directory): events.append(("unpin", path)) @contextmanager - def open_leaf(path): + def open_leaf(path, *, create=True): + assert create assert active == [tmp_path, parent] assert leaf.read_text() == "old" fd = os.open(path, os.O_WRONLY) @@ -582,12 +583,12 @@ def test_native_windows_overwrite_holds_every_parent_and_leaf(tmp_path, monkeypa parents_checked = [] @contextmanager - def open_while_pinned(path): + def open_while_pinned(path, *, create=True): for directory in (root, parent): with pytest.raises(PermissionError): directory.rename(directory.with_name(directory.name + "-moved")) parents_checked.append(directory) - with open_leaf(path) as fd: + with open_leaf(path, create=create) as fd: yield fd def truncate(fd, length): @@ -630,11 +631,11 @@ def test_native_windows_leaf_swap_at_open_never_follows_new_link( original = file_helper._windows_overwrite_fd @contextmanager - def swap(path): + def swap(path, *, create=True): if existing: leaf.rename(root / "original") leaf.symlink_to(outside) - with original(path) as fd: + with original(path, create=create) as fd: yield fd monkeypatch.setattr(file_helper, "_windows_overwrite_fd", swap) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py new file mode 100644 index 0000000000..b708710d36 --- /dev/null +++ b/tests/test_file_helper_rewrite.py @@ -0,0 +1,421 @@ +"""Public in-place byte rewrite and stat on FileHelper.""" + +import errno +import os +import stat +import subprocess +import sys +from contextlib import contextmanager + +import pytest + +from specify_cli.file_helper import ( + FileHelper, SymlinkDeniedError, UnsupportedPathError, +) + + +REL = "parent/file" +# What open(O_NOFOLLOW | O_DIRECTORY) of a symlink raises: Linux/macOS, FreeBSD, NetBSD. +_NOFOLLOW_REFUSALS = { + errno.ELOOP, errno.ENOTDIR, errno.EMLINK, getattr(errno, "EFTYPE", errno.ELOOP), +} + + +def _symlinks_available(tmp_path): + probe = tmp_path / "probe" + try: + probe.symlink_to(tmp_path, target_is_directory=True) + probe.unlink() + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + + +def _seed(tmp_path, content=b"0123456789"): + path = tmp_path / REL + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return path + + +# stat + + +def test_stat_matches_the_entry(tmp_path): + path = _seed(tmp_path) + with FileHelper(tmp_path) as files: + info = files.stat(REL) + native = path.stat() + assert (info.st_dev, info.st_ino, info.st_size) == (native.st_dev, native.st_ino, 10) + assert stat.S_ISREG(info.st_mode) + + +def test_stat_reports_a_directory(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + assert stat.S_ISDIR(files.stat("parent").st_mode) + + +def test_stat_of_a_missing_entry_raises(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.stat("missing") + + +def test_stat_refuses_a_symlink_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + files.stat("link") + with FileHelper(tmp_path, allow_symlinks=True) as files: + assert files.stat("link").st_ino == path.stat().st_ino + + +def test_stat_refuses_a_path_outside_the_root(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(ValueError): + files.stat("../outside") + + +# open_rewrite + + +def test_open_rewrite_writes_in_place_without_truncating(tmp_path): + path = _seed(tmp_path) + inode = path.stat().st_ino + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + assert os.lseek(fd, 0, os.SEEK_CUR) == 0 + assert os.fstat(fd).st_size == 10 + os.write(fd, b"ab\r\n") + assert path.read_bytes() == b"ab\r\n456789" + assert path.stat().st_ino == inode + + +def test_open_rewrite_keeps_the_mode(tmp_path): + path = _seed(tmp_path) + path.chmod(0o640) + before = stat.S_IMODE(path.stat().st_mode) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + os.ftruncate(fd, 0) + os.write(fd, b"new") + assert path.read_bytes() == b"new" + assert stat.S_IMODE(path.stat().st_mode) == before + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX set-user-ID and set-group-ID bits") +def test_open_rewrite_leaves_setid_clearing_to_the_os(tmp_path): + # POSIX lets a write by a process without privilege clear these bits. The + # helper keeps that behaviour rather than restoring them: its result must + # match a plain write to an identical file, with permission bits unchanged. + path = _seed(tmp_path) + control = tmp_path / "control" + control.write_bytes(path.read_bytes()) + for target in (path, control): + target.chmod(0o6750) + before = stat.S_IMODE(path.stat().st_mode) + if not before & (stat.S_ISUID | stat.S_ISGID): + pytest.skip("The filesystem did not keep the set-user-ID or set-group-ID bit") + assert stat.S_IMODE(control.stat().st_mode) == before + + fd = os.open(control, os.O_WRONLY) + try: + os.write(fd, b"new") + os.ftruncate(fd, 3) + finally: + os.close(fd) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + FileHelper.rewrite_descriptor(fd, b"new") + + after = stat.S_IMODE(path.stat().st_mode) + assert path.read_bytes() == b"new" + assert after & 0o777 == before & 0o777 + assert after == stat.S_IMODE(control.stat().st_mode) + + +def test_open_rewrite_closes_the_descriptor(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + with files.open_rewrite(REL) as fd: + pass + with pytest.raises(OSError) as raised: + os.fstat(fd) + assert raised.value.errno == errno.EBADF + + +def test_open_rewrite_never_creates(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + with files.open_rewrite(REL): + pass + assert not (tmp_path / REL).exists() + + +def test_open_rewrite_does_not_create_a_leaf_removed_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path) + original = FileHelper._overwrite_descriptor + + @contextmanager + def remove_first(self, destination, **kwargs): + path.unlink() + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", remove_first) + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + with files.open_rewrite(REL): + pass + assert not path.exists() + + +def test_open_rewrite_refuses_a_directory(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite("parent"): + pass + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_open_rewrite_refuses_a_parent_swapped_for_a_symlink(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + original = FileHelper._overwrite_descriptor + + @contextmanager + def swap_first(self, destination, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + with files.open_rewrite(REL) as fd: + os.write(fd, b"written") + assert raised.value.errno in _NOFOLLOW_REFUSALS + assert (outside / "file").read_bytes() == b"outside" + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX FIFOs") +def test_open_rewrite_refuses_a_fifo_without_blocking(tmp_path): + (tmp_path / "parent").mkdir() + os.mkfifo(tmp_path / REL) + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite(REL): + pass + + +def test_open_rewrite_refuses_a_symlinked_leaf_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + with files.open_rewrite("link"): + pass + with FileHelper(tmp_path, allow_symlinks=True) as files, files.open_rewrite("link") as fd: + os.write(fd, b"ab") + assert (tmp_path / "link").is_symlink() + assert path.read_bytes() == b"ab23456789" + + +# Review regressions + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_stat_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside, longer") + original = FileHelper._posix_directory + + @contextmanager + def swap_first(self, directory, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, directory, **kwargs) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.stat(REL) + assert raised.value.errno in _NOFOLLOW_REFUSALS + + +def test_stat_of_the_root(tmp_path): + with FileHelper(tmp_path) as files: + assert files.stat(tmp_path).st_ino == tmp_path.stat().st_ino + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptors") +def test_open_rewrite_yields_a_blocking_descriptor(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + assert os.get_blocking(fd) + + +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_stat_refuses_a_junctioned_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + project = tmp_path / "project" + project.mkdir() + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(project / "parent"), str(outside)], + check=True, capture_output=True, + ) + with FileHelper(project) as files, pytest.raises(UnsupportedPathError): + files.stat(REL) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_stat_does_not_follow_a_root_replaced_by_a_symlink(tmp_path): + root = tmp_path / "root" + root.mkdir() + other = tmp_path / "other" + other.mkdir() + with FileHelper(root) as files: + root.rename(tmp_path / "moved") + root.symlink_to(other, target_is_directory=True) + assert stat.S_ISLNK(files.stat(".").st_mode) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX FIFOs") +def test_open_rewrite_refuses_a_nonregular_leaf_swapped_in_after_preflight(tmp_path, monkeypatch): + # A FIFO with a reader opens for writing, so only the descriptor check can refuse it. + path = _seed(tmp_path) + real_open = os.open + original = FileHelper._overwrite_descriptor + leaf: list[int] = [] + readers: list[int] = [] + + def open_(name, flags, *args, **kwargs): + fd = real_open(name, flags, *args, **kwargs) + if os.fspath(name) == "file": + leaf.append(fd) + return fd + + @contextmanager + def swap_first(self, destination, **kwargs): + path.unlink() + os.mkfifo(path) + readers.append(real_open(path, os.O_RDONLY | os.O_NONBLOCK)) + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) + entered = False + try: + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite(REL): + entered = True + finally: + for fd in readers: + os.close(fd) + monkeypatch.undo() + assert not entered + assert len(leaf) == 1 + with pytest.raises(OSError) as raised: + os.fstat(leaf[0]) + assert raised.value.errno == errno.EBADF + + +def test_rewrite_descriptor_replaces_and_truncates_from_any_offset(tmp_path): + target = tmp_path / "file.txt" + target.write_bytes(b"a much longer original\n") + inode = target.stat().st_ino + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + os.lseek(fd, 0, os.SEEK_END) + FileHelper.rewrite_descriptor(fd, b"short\n") + assert target.read_bytes() == b"short\n" + assert target.stat().st_ino == inode + + +def test_rewrite_descriptor_flushes_after_writing(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + seen = [] + real_fsync = os.fsync + + def fsync(fd): + seen.append(os.fstat(fd).st_size) + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + FileHelper.rewrite_descriptor(fd, b"newer\n") + assert seen == [len(b"newer\n")] + + +def test_rewrite_descriptor_raises_when_a_write_makes_no_progress(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + monkeypatch.setattr(os, "write", lambda fd, data: 0) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + with pytest.raises(OSError, match="no progress"): + FileHelper.rewrite_descriptor(fd, b"new\n") + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS F_FULLFSYNC") +@pytest.mark.parametrize("code, raises", [(errno.ENOTSUP, False), (errno.EIO, True)]) +def test_rewrite_descriptor_raises_only_real_full_fsync_errors(tmp_path, monkeypatch, code, raises): + import fcntl + + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + real_fcntl = fcntl.fcntl + + def fail(fd, command, *args): + if command == fcntl.F_FULLFSYNC: + raise OSError(code, os.strerror(code)) + return real_fcntl(fd, command, *args) + + monkeypatch.setattr(fcntl, "fcntl", fail) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + if raises: + with pytest.raises(OSError): + FileHelper.rewrite_descriptor(fd, b"new\n") + else: + FileHelper.rewrite_descriptor(fd, b"new\n") + if not raises: + assert target.read_bytes() == b"new\n" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX append-mode descriptors") +def test_rewrite_descriptor_refuses_an_append_mode_descriptor(tmp_path): + target = tmp_path / "file.txt" + target.write_bytes(b"original bytes") + fd = os.open(target, os.O_WRONLY | os.O_APPEND) + try: + with pytest.raises(OSError, match="append-mode"): + FileHelper.rewrite_descriptor(fd, b"new") + finally: + os.close(fd) + assert target.read_bytes() == b"original bytes" + + +def _short_writes(monkeypatch, fail_after=None): + """Make ``os.write`` accept at most 3 bytes a call, optionally failing after some calls.""" + real_write = os.write + calls = [] + + def write(fd, data): + calls.append(fd) + if fail_after is not None and len(calls) > fail_after: + raise OSError(errno.EIO, "I/O error") + return real_write(fd, bytes(data[:3])) + + monkeypatch.setattr(os, "write", write) + return calls + + +def test_rewrite_descriptor_retries_short_writes(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"a much longer original\n") + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + calls = _short_writes(monkeypatch) + FileHelper.rewrite_descriptor(fd, b"replacement\n") + monkeypatch.undo() + assert len(calls) > 1 + assert target.read_bytes() == b"replacement\n"