Expand description
Filesystem-level copy-on-write helpers.
Heddle’s worktree materializer needs the storage win of pointing
N worktrees at the same blob bytes (so checking out the same state
to many sibling worktrees costs ~1× disk, not N×) without the
mutation hazard that hardlinks bring. With hardlinks, an in-place
write — chmod +w file && echo new > file, O_TRUNC, etc. —
mutates the shared inode, corrupting every other worktree that
points at the same blob.
Filesystem reflinks (a.k.a. CoW clones) solve this: the destination starts out sharing physical blocks with the source, but the first write to either side automatically forks the underlying allocation. The OS guarantees isolation even if an agent strips the read-only bit and overwrites the file in place.
Platform support:
- macOS / APFS:
clonefile(2)from<sys/clonefile.h>. True CoW. - Linux / btrfs / XFS-with-reflinks / ZFS:
ioctl(dest_fd, FICLONE, src_fd). - Anywhere else (or when reflink isn’t supported by the underlying filesystem): caller falls back to a real copy.
The functions here return Ok(true) on a successful clone,
Ok(false) when the kernel reported the operation isn’t supported
on this filesystem (so the caller should fall back to a real copy
and remember to skip future reflink attempts in this batch), and an
Err for genuine I/O errors that the caller should surface.
Functions§
- clonefile_
or_ copy - Reflink if possible, otherwise fall back to a real copy. Returns
the same
Ok(true)/Ok(false)discriminator astry_reflink—truewhen the OS gave us a CoW clone,falsewhen we paid the full copy cost. Either way, onOkthe destination exists and has the source’s bytes. - filesystem_
supports_ reflink - Test whether the filesystem at
parent_dirsupports reflinks by trying one against a temp source/dest pair. Returnstrueon success. Useful for tests that want to soft-skip on filesystems without CoW support, and for any caller that wants a runtime capability check before asserting on reflink-specific properties. - try_
reflink - Try a filesystem-level reflink (copy-on-write clone) from
sourcetodest. On success the destination has its own inode and shares physical blocks with the source until either side is modified.