I was recently writing about the problem of disk space usage when building with Bazel due to its many caches. That led me to pay more attention to the work being done in this area, and I discovered that Bazel 9.3.0 is expected to make better use of copy-on-write cloning on macOS #30776 to avoid unnecessarily duplicating files between the disk cache and the output base.
On APFS, this essentially means copy-on-write: the cloned files initially share the same underlying data blocks, so they don’t immediately take up twice the physical disk space. If either copy is modified, the filesystem only needs to allocate storage for the changed blocks.
Using APFS clones from Swift
Naturally, I got interested in learning how this feature works, and it turns out to be pretty simple. There is a low-level API function, clonefile(...), which does exactly what you would expect: it creates a copy-on-write clone of a file.
If I were to wrap that function in Swift, here is roughly how I would do it. In production code, I would also provide better error handling:
func clone(from source: String, to destination: String) -> Bool {
let source = source.cString(using: .utf8)
let destination = destination.cString(using: .utf8)
let result = clonefile(source, destination, 0)
return result == 0
}
I recommend taking a look at its man page to learn more about it.
Conclusion
I wanted to share this because I feel like APFS cloning is not talked about enough. It’s a simple API backed by a pretty powerful filesystem feature, and I hope you find it handy someday.