atomicfile

package module
v2.9.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2026 License: Apache-2.0 Imports: 16 Imported by: 5

README

atomicfile

Go Reference Go version Test coverage Mutation OpenSSF Best Practices OpenSSF Scorecard

Crash-safe atomic file writes for Go

A standalone Go library providing atomic file writes (temp→fsync→rename→dir-fsync), path cleaning with os.Root-based containment, bounded reads, and streaming writes. Standard-library only, no external runtime dependencies.

Every write is os.Root-confined: the *InRoot APIs use the caller's root directly, and the absolute-path APIs open the target's parent directory as a root and write through it.

Platform Support

Linux only (including Docker/containers). Windows is unsupported by design: os.Rename cannot guarantee atomicity on Windows (golang/go#22397). macOS/BSD may work but is untested.

Install

go get github.com/cplieger/atomicfile/v2@latest

Usage

package main

import (
	"context"
	"log"
	"os"
	"strings"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	ctx := context.Background()

	// Atomic write with default mode (0644). The returned Result reports the
	// final path and whether the write is crash-durable.
	res, err := atomicfile.WriteFile(ctx, "/tmp/data.txt", []byte("hello"))
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("wrote %s (durable=%v)", res.Path, res.Durable)

	// Atomic write with custom mode.
	atomicfile.WriteFile(ctx, "/tmp/secret.txt", []byte("s3cr3t"),
		atomicfile.WithMode(0o600))

	// Streaming write from an io.Reader (mode via WithMode).
	atomicfile.WriteReader(ctx, "/tmp/stream.txt", strings.NewReader("streamed"),
		atomicfile.WithMode(0o644))

	// PendingFile for incremental writes (mirrors google/renameio).
	pf, _ := atomicfile.NewPendingFile(ctx, "/tmp/pending.txt")
	defer pf.Cleanup()
	pf.Write([]byte("incremental"))
	pf.Commit(ctx)

	// Preserve existing file permissions across replace.
	atomicfile.WriteFile(ctx, "/tmp/data.txt", []byte("updated"),
		atomicfile.WithPreserveMode())

	// Auto-create parent directories.
	atomicfile.WriteFile(ctx, "/tmp/nested/dir/file.txt", []byte("deep"),
		atomicfile.WithMkdirMode(0o755))

	// Skip fsync for speed (atomicity without durability).
	atomicfile.WriteFile(ctx, "/tmp/cache.txt", []byte("fast"),
		atomicfile.WithNoSync())

	// Confined I/O through an *os.Root (Go 1.24+): name is relative to the root,
	// and a symlink or ".." in it can never escape the root's tree.
	root, _ := os.OpenRoot("/tmp")
	defer root.Close()
	atomicfile.WriteFileInRoot(ctx, root, "rooted.txt", []byte("confined"))

	// Read it back through the same root: open via the root (so the path stays
	// confined), then bound the read with ReadBoundedFile.
	rf, _ := root.Open("rooted.txt")
	defer rf.Close()
	rooted, _ := atomicfile.ReadBoundedFile(ctx, rf, 1<<20)
	log.Printf("read %d confined bytes", len(rooted))

	// Bounded read.
	data, _ := atomicfile.ReadBounded(ctx, "/tmp/data.txt", 1<<20)
	log.Printf("read %d bytes", len(data))
}

API

Write Functions

All write primitives return (Result, error); inspect Result.Durable for crash durability (see Result and Durability for the nil-error contract).

  • WriteFile(ctx, path, data, opts ...Option) (Result, error): atomic write (default mode 0644)
  • WriteReader(ctx, path, r, opts ...Option) (Result, error): atomic write from io.Reader (uses the io.WriterTo fast path when available; mode via WithMode)
  • WriteFileInRoot(ctx, root, name, data, opts ...Option) (Result, error): atomic write of data to name relative to an *os.Root; every filesystem op runs through the root, so a symlink or .. in name cannot escape its tree
  • WriteReaderInRoot(ctx, root, name, r, opts ...Option) (Result, error): same, streaming from an io.Reader
Streaming Writer
  • NewPendingFile(ctx, path, opts ...Option) (*PendingFile, error): open a temp file for incremental writing (mode via WithMode)
  • NewPendingFileInRoot(ctx, root, name, opts ...Option) (*PendingFile, error): same, confined to an *os.Root: the temp, rename, and parent-dir fsync all run through the caller's root, which stays caller-owned (keep it open through Commit/Cleanup)
  • (*PendingFile).Commit(ctx) (Result, error): chmod + fsync + close + rename + dir-fsync (finalize). Idempotent: repeated calls return the first result. Returns ErrAborted if called after Cleanup.
  • (*PendingFile).Cleanup() error: close + remove (abort; no-op after Commit, idempotent). Safe to defer immediately after NewPendingFile.

PendingFile embeds *os.File, so the full io.Writer/io.ReaderFrom/fmt.Fprintf surface is available, and Name() reports the staged temp's path for inspection before Commit publishes it. A WithMaxBytes cap is enforced as you write (BytesWritten() reports the count, Truncate re-syncs it, and a call that would cross the cap is rejected whole) and re-verified against the staged file's actual size at Commit, so bytes staged outside the tracked stream (WriteAt, Write after Seek, a reopen of the temp by path) cannot publish an over-cap file either.

Read Functions
  • ReadBounded(ctx, path, maxBytes) ([]byte, error): size-checked read; returns ErrFileTooLarge past the limit
  • ReadBoundedFile(ctx, f, maxBytes) ([]byte, error): size-checked read from an already-open *os.File (the seam for reading a file opened through an *os.Root); the caller owns and closes f
  • OpenRegularInRoot(root, name) (*os.File, os.FileInfo, error): the open half of ReadBoundedInRoot, which is now literally this plus ReadBoundedFile. Opens name through the root read-only and non-blocking, stats the OPEN HANDLE rather than the pathname, and refuses a directory, FIFO, device node or socket with ErrNotRegular. The caller owns and closes the descriptor.
  • OpenRegular(path) (*os.File, os.FileInfo, error): the ambient-path sibling, for a full path into a directory the caller trusts. O_NOFOLLOW makes the kernel refuse a symlink under the name (ErrSymlinkTarget), which no check-then-open sequence can do without a race; the path itself goes through the ValidatePath rule. This does not change ReadBounded, which still follows symlinks by design.

Both openers exist because the descriptor is what a consumer cannot rebuild from bytes: a caller streaming the file through a decoder or decryptor never materializes it, and a caller caching the file needs the FileInfo the bytes came from to record a FileIdentity. Binding the shape check, the identity and the read to ONE descriptor is the point — a second stat of the pathname lets a rename in between decode one generation's bytes while recording another's identity, and turns every non-regular-file rejection back into a check-then-open race. Neither opener pins the ancestor components; OpenParentInRoot does that.

Confined Traversal and Removal

An *os.Root confines a path but does not pin it: a root deliberately follows a symlink component that stays inside its tree, so a multi-component name that is stat-ed and then operated on can address two different files if an ancestor directory is swapped for a symlink in between. Confinement still holds (nothing outside the root is reachable) and the operation lands somewhere inside the tree the caller never inspected. These two close that gap for callers working in a tree others can write to — a co-mounted Docker volume, a shared NFS export.

  • WalkDirInRoot(ctx, root, fn fs.WalkDirFunc) error: stream a confined tree. Each directory is read in fixed 256-entry ReadDir batches instead of one materialized (and sorted) inventory, exactly ONE directory handle is open at a time (what the walk carries between directories is a queue of names), each directory is opened O_DIRECTORY so a named pipe swapped in for a directory is refused with ENOTDIR rather than blocking the caller's goroutine in open(2), and a symlinked directory is never descended. The callback is an fs.WalkDirFunc, called exactly as fs.WalkDir calls one — the root first as ".", then each entry pre-order, a directory that cannot be opened or finished reported through the callback for its own path, fs.SkipDir/fs.SkipAll honoured. Two deliberate differences: entries arrive in directory order (sorted within a batch only, because a global sort is the materialization this avoids), and a directory's own entries are all visited before the walk descends into its subdirectories. The walk stops between batches once ctx is done; a caller wanting per-entry cancellation checks ctx in the callback. Walk a subtree by passing root.OpenRoot(sub).
  • OpenParentInRoot(root, name) (parent *os.Root, base string, err error): open name's parent directory as its own root, pinned. Every component is Lstat-ed (a symlink is refused, not followed), required to be a real directory, opened as a root, and confirmed with os.SameFile against the directory that was inspected, so a component replaced mid-open is refused too. Naming only base through parent afterwards removes every ancestor from the operation's path. The returned root is always a fresh handle the caller closes — including for a flat name, where it is a second handle on the root's own directory — so the close is unconditional and never closes the caller's root. A vanished component matches fs.ErrNotExist (the benign racing-deletion case), a refused one does not.
  • RemoveFileInRoot(root, name) error: that descent applied to an unlink. Only a regular file is removed; a directory, symlink, device node, socket or FIFO wearing the name is refused with ErrNotRegular and left as found. A missing file is reported (fs.ErrNotExist) rather than swallowed — whether an already-gone name is success is the caller's judgement.

CleanupStaleTempsInRoot uses both: it enumerates through WalkDirInRoot (so a large or hostile directory is not materialized before the sweep sees its first entry) and unlinks every candidate through a pinned parent.

Private Directories and Enforced Modes
  • EnforceMode(f *os.File, want os.FileMode) (os.FileMode, error): fchmod the open handle to want, then fstat the same handle and return the mode the filesystem actually stored; a mismatch is ErrModeNotStored, naming both modes. Works for a file or a directory, since both are an *os.File.
  • EnsurePrivateDir(dir string, opts ...Option) (PrivateDir, error): establish custody of one directory level only the effective uid may enter — mkdir 0700, open O_DIRECTORY|O_NOFOLLOW, fstat the handle, require the owner uid, repair the mode if we created it, refuse it if we did not.
type PrivateDir struct {
	Mode     os.FileMode // the mode the filesystem stored, read back from the handle
	Created  bool        // this call created the directory
	Repaired bool        // the created directory's mode had to be corrected
}

A mode argument to mkdir(2) or open(2) is a request, not a result. umask narrows it, and a filesystem carrying an inheritable ACL can widen the outcome regardless of what was asked — measured on a ZFS nfs4acl dataset, an inheritable group@:rwx ACE stores 0770 for a 0o700 mkdir, and a child of an already-0700 parent comes back 0770 too, so tightening the parent does not cover it. chmod(2) is the only call that sets a mode; a caller that stops there has issued a second request rather than confirmed a result. EnforceMode is the chmod and the re-stat, on one descriptor, because a chmod-then-stat by name can chmod one object and certify another if the name is swapped in between.

EnsurePrivateDir composes that into the sequence a process needs when its private directory lives inside a parent other users can write (a state directory under /tmp, an admin-socket directory):

  • mkdir 0700, remembering whether this call created the level. os.MkdirAll cannot substitute: it stats the path, follows a symlink, finds a directory and returns nil, so it cannot tell "I created this" from "something was already here" — the distinction every decision below turns on.
  • Open O_DIRECTORY|O_NOFOLLOW|O_RDONLY. The kernel refuses a planted symlink instead of following it (ErrSymlinkTarget), refuses anything that is not a directory (ErrNotDirectory), and cannot be stalled indefinitely by a planted FIFO.
  • fstat the handle, then require os.Geteuid() to own it (ErrNotOwned). Ownership, not just mode: a perfectly-moded 0700 directory owned by another uid passes every other check and its owner can still replace it — with a symlink the caller then follows — after the verdict returns.
  • If this call created it, EnforceMode to 0700. That is the ACL repair, and it is safe precisely because we made the directory: no other writer has ever held that name. A pre-existing directory is refused instead, unless the caller passes WithRepairOwnedDir() — which repairs it, because the euid-ownership check has already proved the directory is the caller's own (see the option table). That option exists so a mode fix does not become an outage the first time an app meets a directory an earlier release of itself created.
  • If it pre-existed, it is never chmod'ed and is refused when any group or other bit is set (ErrModeTooOpen). Repairing a directory another principal made would take over their name and hand them whatever gets written under it.

One level per call, deliberately. dir's parent is not created, inspected, or vouched for; a multi-level path is a loop over the levels, outermost first, because only the caller knows which levels are its own.

The verdict is point-in-time. It proves what was true of one inode while a handle was open on it. It does not pin the directory for the caller's later use: the handle is closed before the call returns, so a subsequent ReadDir, Remove, Open or Mkdir through the pathname re-resolves every component and re-opens the window the check closed. What would close that gap is acting through a retained handle rather than a name — the openat(2)-relative operations of an *os.Root — which is a different API shape: hold the directory open for its whole lifetime and name only leaves inside it.

Of the functional options only WithLogger is consulted, for the one Warn a mode repair emits (a filesystem that ignores mode requests is news for every other mkdir in the program too). The mode is not a parameter: a "private directory" with a caller-chosen mode is a different primitive.

Utilities
  • CleanupStaleTemps(dir, maxAge, opts ...Option) (removed int, err error): remove orphaned temp files left by interrupted writes, returning how many were removed. Only files matching the package's exact temp shape (.atomicfile-<digits>.tmp) and older than maxAge are reclaimed; caller-owned files that merely share the prefix or suffix (.atomicfile-notes.tmp, config.tmp-backup) are never touched. Each candidate is re-checked immediately before removal, so a same-named fresh temp created during the scan is spared.
  • Identify(info os.FileInfo) FileIdentity + Matches / Changed / Recorded / ModTime: reload-staleness comparison for a reader caching a file another process publishes. See Reload staleness.
  • TempName() string and IsPackageTemp(name string) bool: the temp-name convention as a contract. TempName returns a fresh name of the exact shape the sweeps reclaim; IsPackageTemp reports whether a directory entry's name is one. Use them instead of rebuilding .atomicfile-<digits>.tmp by hand — os.CreateTemp(dir, ".atomicfile-*.tmp") only matches because Go happens to substitute decimal digits for *, which its documentation does not promise.
  • ValidatePath(path string) error: the path gate the absolute-path functions apply (WriteFile, WriteReader, NewPendingFile, ReadBounded), for a caller that has to accept or refuse a path before it writes — a config value read at startup, a CLI flag, a request field. nil means acceptable; otherwise it returns the same error the write would: ErrEmptyPath, or ErrUnsafePath for an embedded NUL or a path that is not absolute once cleaned. It delegates to the one private validator the writes use, so an acceptance here and a rejection at write time cannot disagree. filepath.IsAbs is the usual stand-in and is a different rule: it accepts "/tmp/a\x00b", which every write here refuses. Nothing on the filesystem is consulted — the path need not exist and its parent need not be a directory — so nil says the path is well formed, not that a write there will succeed (ProbeWritable answers that, by writing). Being absolute is not containment: filepath.Clean normalizes .., so use the *os.Root-backed APIs to confine writes to a tree.
Writability Probe
  • ProbeWritable(ctx, dir, opts ...Option) (ProbeResult, error): prove a directory is genuinely writable by doing what a write does — create a temp file, write and flush a byte, close it, unlink it — and report which stage failed. dir may be relative; WithMkdirMode creates it first, WithNoSync skips the flush.
  • ProbeWritableInRoot(ctx, root, name, opts ...Option) (ProbeResult, error): the same probe confined to an *os.Root (name is relative to it, "." for the root itself), for a caller that already holds a root over the directory it is about to write to. An escaping name is refused by the root.
type ProbeResult struct {
	Err    error      // the failure from Stage, unwrapped to the filesystem error
	Dir    string     // directory probed
	Name   string     // probe file's base name; always satisfies IsPackageTemp
	Stage  ProbeStage // first stage that failed, or ProbeStageNone
	Leaked bool       // probe file still on disk
}

A stat of the mode bits is not an answer: an NFS or FUSE mount, a read-only bind mount, and a Docker volume owned by another UID all present a writable-looking directory that refuses the first write. The stages are the whole ladder (ProbeStageMkdir, Create, Write, Sync, Close, Remove), because a filesystem can accept the directory entry yet reject the first data write, surface a delayed failure only at sync or close, or accept everything and deny the unlink.

Policy stays with the caller. A stage failure is reported in the ProbeResult, never as the error return — err != nil means only that the probe could not be attempted (empty dir, cancelled context). res.OK() is the everything-passed answer; res.Writable() is the split for a caller that wants to warn about a failed cleanup and keep running, since a failure at ProbeStageClose or later still proves the directory took the bytes.

The probe file is named with TempName(), so a probe orphaned by a crash — or left behind by a directory that denies the unlink — is reclaimed by CleanupStaleTemps like any other temp, by construction rather than by a naming convention each caller reproduces.

ctx is checked once, before anything is created; the stages are single filesystem calls the OS does not make interruptible, and a probe that has begun always runs its own cleanup, so guard a possibly-wedged mount with your own timeout around the call.

Reload staleness

A process that caches a file written by someone else needs to know, from a stat alone, whether its in-memory copy is still current. The correct test is mtime equality AND os.SameFile identity, and it is knowledge about this package's write barrier — which is why the primitive lives here:

// after loading
id := atomicfile.Identify(info)

// on every poll
info, err := os.Stat(path)
if err != nil { /* caller's policy */ }
if id.Changed(info) {
	// reload, then re-Identify
}

Both legs are load-bearing, because two different write mechanisms change a file's content and each defeats one half of the naive check:

  • An in-place writer (os.WriteFile, an editor, truncate-and-write) keeps the same inode and moves the mtime forward. An identity-only check calls that unchanged.
  • A publish-by-rename writer — every write in this package — installs a different inode. Normally its mtime differs too, but it need not: a backup restore, rsync -t, tar -xp, or any re-publication of an archived generation lands new content carrying the old timestamp. An mtime-only check calls that unchanged, and the stale copy is then served until something else happens to touch the file.

Size is deliberately not part of the comparison: a same-size replacement is exactly the case a size check misses, and a differing size is already caught by one of the two legs.

The zero FileIdentity records nothing and reports Changed, which is the fail direction a cache wants — a spurious reload costs one read, a missed reload serves stale data indefinitely. FileIdentity is a comparison primitive, not a policy: degradation states, stat-error handling, and re-stat cadence stay with the caller.

Result and Durability

type Result struct {
	Path    string // cleaned final path (absolute for the package-level writers; root-relative for WriteFileInRoot/WriteReaderInRoot)
	Durable bool   // true only when file + parent-dir fsync both completed
}

Every atomic write follows the sequence: create temp file → write data → fsync temp → close → rename to final path → fsync parent directory. After a crash the file contains either the complete old content or the complete new content, never a partial write. The directory fsync makes the rename durable even if the system loses power immediately after the call returns.

A nil error means the data reached its final path: the write either fully succeeded or, at worst, was renamed into place but the parent-directory fsync failed (for example an EIO from a failing disk; the rename has already completed, and the write logs the fsync failure at Warn). Result.Durable distinguishes those two outcomes, so a caller that cares about crash durability inspects Result.Durable rather than decoding error types. A non-nil error always means the data did not reach its final path.

Callers that require strict durability treat Durable == false as actionable (retry or alert); callers that only need atomicity can ignore it or use WithNoSync() to skip the directory fsync entirely.

Note on auto-created directories. When WithMkdirMode creates new parent directories, only the file's immediate parent is fsynced. The newly created intermediate directories are not fsynced into their own parents, so the durability guarantee above applies only when the full parent path already exists. If you need durability into a freshly created directory tree, create and fsync the directories before writing.

Functional Options

All write functions accept variadic Option values. Omit options for defaults.

Option Description
WithLogger(l) Custom *slog.Logger for diagnostic output (default: slog.Default())
WithMode(mode) File permission (default: 0o644)
WithMkdirMode(mode) Create the parent directory (and missing ancestors) with this mode before writing. Without it, a missing parent is an error.
WithRepairOwnedDir() EnsurePrivateDir only: repair a pre-existing directory whose owner is already the effective uid, instead of refusing it. For adopting your own past output; ignored by writes.
WithPreserveMode() Stat the target and reuse its mode (like renameio.WithExistingPermissions), falling back to WithMode if it does not exist or cannot be stat-ed
WithPreserveOwnership() Stat the target and chown the temp to match its uid/gid (requires CAP_CHOWN; no-op when the target is absent, cannot be stat-ed, or off Unix)
WithNoSync() Skip fsync for speed (atomicity without durability). Result.Durable is then always false.
WithMaxBytes(n) Cap staged content at n bytes, the write-side mirror of ReadBounded. Over-cap writes match ErrFileTooLarge and leave the previous target intact. n <= 0 = no cap.
WithAllowSymlinkTarget() Permit writing to a symlink path (default: refuse with ErrSymlinkTarget)

Errors

Sentinel Meaning
ErrEmptyPath The path argument was empty
ErrUnsafePath The path is not absolute or contains a null byte
ErrFileTooLarge The file exceeded the ReadBounded size limit, or content exceeded a WithMaxBytes write cap
ErrSymlinkTarget The target is a symlink and WithAllowSymlinkTarget was not set; or OpenRegular refused one
ErrNotRegular Name resolved to a non-regular file (dir, FIFO, device, socket); the mode is named
ErrNotDirectory EnsurePrivateDir: the name is occupied by a file, FIFO, device node or socket
ErrNotOwned EnsurePrivateDir: the directory's owner is not the effective uid (or could not be determined)
ErrModeTooOpen EnsurePrivateDir: a pre-existing dir grants group/other access, no WithRepairOwnedDir
ErrModeNotStored EnforceMode: the mode read back after the chmod is not the mode that was asked for
ErrAborted PendingFile.Commit was called after Cleanup aborted the pending write

The package-level path check is not a containment boundary. filepath.Clean normalizes any .. in an absolute path rather than rejecting it (for an absolute path there is nothing to escape), so ErrUnsafePath only guards against a non-absolute or null-byte path. Callers that need to confine writes to a directory tree use the *os.Root-backed write APIs (WriteFileInRoot / WriteReaderInRoot). Callers that need to confine reads should open the file through an *os.Root and pass that already-confined handle to ReadBoundedFile, which then applies the same size and context bounds.

Failures in the write barrier (open destination / create temp, write, chmod, sync, close, rename) are reported as *WriteError{Err, Phase}, where Phase is one of PhaseTempCreate, PhaseTempWrite, PhaseTempChmod, PhaseTempSync, PhaseTempClose, or PhaseRename. PhaseTempCreate covers opening the destination for writing (a missing parent without WithMkdirMode surfaces here) as well as creating the temp file inside it. Pre-barrier failures keep their own error types: path-validation and symlink failures use the sentinels above, context failures wrap the standard-library context error (context.Canceled / context.DeadlineExceeded), and a WithMkdirMode parent-directory creation failure wraps the underlying os error behind the atomicfile: prefix. All are inspectable with errors.Is / errors.As, and a *WriteError always means the data did not reach its final path.

By default, all write functions refuse to write to a path that is currently a symlink, returning ErrSymlinkTarget. os.Rename replaces the symlink itself rather than the file it points to, which is rarely the caller's intent and can lead to data loss or security issues.

To opt in to writing through a symlink (replacing the symlink with a regular file), use WithAllowSymlinkTarget(). To write to the link's target instead, resolve it with filepath.EvalSymlinks first.

Metadata reads under WithAllowSymlinkTarget. The symlink-following stat that WithPreserveMode / WithPreserveOwnership perform runs through an os.Root of the target's parent directory. A symlink target whose destination is absolute or escapes that directory is not followed for the metadata read: preserve-mode falls back to the WithMode value and preserve-ownership becomes a no-op for such links (the write itself still replaces the link). Links resolving within the parent directory are followed as normal.

Reads behave differently: ReadBounded follows symlinks by design (os.Open resolves them), so it does NOT refuse a symlink at path. When reading from a directory writable by a less-trusted principal, confine the path yourself: open the file through an *os.Root (Go 1.24+) and read it with ReadBoundedFile, which applies the same size and context bounds without following symlinks out of the root. OpenRegularInRoot is that open, already written; OpenRegular is the ambient-path form for a caller holding a full path into a directory it trusts, and it is the one read entry point that does refuse a symlink under the name — O_NOFOLLOW has the kernel refuse the open, which a check-then-open sequence cannot do without a race.

An *os.Root is not the whole answer for a multi-component name, because it follows a symlink component that stays inside its tree: two operations on one such path can land on two different files if an ancestor directory is swapped in between. OpenParentInRoot and RemoveFileInRoot pin the ancestors — see Confined Traversal and Removal.

Unsupported by Design

Feature Rationale
Windows rename-over semantics Target platform is Linux. os.Rename is atomic on Linux. Windows cannot guarantee atomicity (golang/go#22397). google/renameio also refuses Windows.
fs.FS interop fs.FS is a read-only interface. Atomic writes are inherently outside its scope.
Atomic symlink replacement Out of scope. Use google/renameio if needed.
Umask-aware permissions The library uses Chmod for exact permissions (ignoring umask). This is the correct secure default for server/CLI tools. Equivalent to renameio's WithStaticPermissions.
TempDir cross-mount detection Temp files are always created in the target directory (same mount point), the only correct approach for atomic rename.

Contributing

Issues and PRs are welcome. See CONTRIBUTING.md for the conventions and how to run the checks locally.

Disclaimer

This project is built with care and follows security best practices, but it is intended for personal / self-hosted use. No guarantees of fitness for production environments. Use at your own risk.

This project was built with AI-assisted tooling using Claude, GPT, and Kiro. The human maintainer defines architecture, supervises implementation, and makes all final decisions.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package atomicfile provides crash-safe atomic file writes via the temp → fsync → rename → dir-fsync sequence, with path validation and bounded reads. Standard-library only.

Result and durability

The write primitives (WriteFile, WriteReader, WriteFileInRoot, WriteReaderInRoot, and PendingFile.Commit) return a Result alongside an error. A nil error means the data reached its final path; the write either fully succeeded or, at worst, was renamed into place but the parent-directory fsync failed. Result.Durable distinguishes those two outcomes: it is true only when both the file and its parent directory were fsynced, so a caller that cares about crash durability inspects Result.Durable rather than decoding error types. A non-nil error always means the data did NOT reach its final path.

Temp files

Every temp file this package creates is named ".atomicfile-<digits>.tmp" (the digits are a crypto/rand decimal string). CleanupStaleTemps reclaims orphaned temps of exactly that shape and nothing else, so it never deletes a caller-owned file.

That shape is part of the API, not an implementation detail, because a caller staging its own file in a swept directory has to agree with it: TempName produces a name the sweeps reclaim and IsPackageTemp reports whether a name is one, so the agreement is a contract a test can pin rather than a convention rebuilt from os.CreateTemp's undocumented substitution.

Path validation

ValidatePath is the acceptance check the absolute-path entry points apply, exported for callers that have to accept or refuse a path long before they write to it — a config value read at startup, a CLI flag, a request field. filepath.IsAbs is the usual stand-in and admits a path with an embedded NUL that every write here refuses, so validating with it accepts input the write path rejects later. The exported gate delegates to the same private validator the writes use, so the two verdicts cannot drift; it touches nothing on disk, which also means a nil answer says the path is well formed, not that a write will succeed (that is ProbeWritable's question).

Writability probes

ProbeWritable and ProbeWritableInRoot answer "can this process actually write here?" — the preflight question a stat of the mode bits gets wrong on an NFS or FUSE mount, a read-only bind mount, or a Docker volume owned by another UID. They walk the full ladder a real write walks (mkdir, create, write, sync, close, remove) and report which stage failed in a ProbeResult rather than as an error, so a caller that warns on a failed cleanup and one that treats it as fatal both get what they need. The probe file carries the package temp shape, so a probe leaked by a crash is swept like any other orphan.

Size bounds

ReadBounded and ReadBoundedFile refuse to read a file past a byte limit, and WithMaxBytes mirrors that bound on the write side across every write primitive: a writer that also owns the reader can refuse to persist a file its own read path would refuse to load, instead of failing open on the next read. The cap is enforced twice: on the staged stream as bytes arrive, and against the staged file's actual size at the durability barrier before publication, so content staged outside the streaming interfaces cannot publish either. Both directions report ErrFileTooLarge, and a capped write always leaves the previous file at the target path intact.

Safe opens

OpenRegularInRoot and OpenRegular hand back the OPEN DESCRIPTOR of a file already known to be a regular one, which is the reusable half of the read sequence: open (confined to a root, or refusing a final-component symlink outright), stat the handle rather than the pathname, refuse a directory, FIFO, device node or socket. ReadBoundedInRoot is now literally OpenRegularInRoot plus ReadBoundedFile, so the sequence has one home.

A caller that STREAMS the file through a decoder or decryptor never materializes its bytes, and a caller caching the file needs the FileInfo the bytes came from in order to record a FileIdentity; neither can use a []byte-returning helper. Both are the same argument: binding the shape check, the identity and the read to ONE descriptor is what closes the window a second pathname observation opens, where a rename in between lets a caller decode one generation's bytes while recording another's identity and turns every non-regular-file rejection back into a check-then-open race.

The two refusals differ because the mechanisms do. The root-confined form bounds where the open can land but still traverses a symlink inside the tree (that is what an *os.Root promises); the ambient form opens O_NOFOLLOW, so the kernel itself refuses a symlink under the name and reports ErrSymlinkTarget, the same vocabulary the write side uses. Neither pins the ancestor components — OpenParentInRoot does that.

Private directories and enforced modes

A mode passed to mkdir(2) or open(2) is a REQUEST. umask narrows it, and a filesystem carrying an inheritable ACL can widen the result regardless of what was asked — measured on a ZFS nfs4acl dataset, an inheritable group@:rwx ACE stores 0770 for a 0o700 mkdir, and tightening the parent does not cover it. chmod(2) is the only call that SETS a mode, and a caller that stops there has issued a second request rather than confirmed a result.

EnforceMode closes that loop on an OPEN HANDLE: fchmod then fstat the same descriptor, returning the mode the filesystem actually stored and refusing a mismatch with ErrModeNotStored. It takes an *os.File, so a file and a directory are the same call, and it observes no pathname — a chmod-then-stat by name can chmod one object and certify another.

The write path uses it on itself, in two places. The staging file is created owner-only and PROVED owner-only before the caller's payload goes into it — the temp has to share the target's parent directory, so on a widening filesystem it would otherwise hold the payload group-readable and group-writable for the whole write. Then WithMode's mode is enforced rather than merely requested before the rename publishes it, so a filesystem that refuses the mode fails the write instead of publishing a wider file.

EnsurePrivateDir is the custody composition around it, for a process establishing a directory only its own user may enter inside a parent others can write: mkdir 0700 recording whether THIS call created it, open O_DIRECTORY|O_NOFOLLOW so a planted symlink is refused rather than followed and a planted FIFO cannot stall the open, fstat the handle, require the effective uid to own it, then EnforceMode a directory it created (the ACL repair, safe because nobody else ever held that name) while REFUSING a pre-existing one that grants group or other access (repairing another principal's directory would take over their name). One level per call: a multi-level path is the caller's loop, because only the caller knows which levels are its own.

The verdict is POINT-IN-TIME. It proves what was true of one inode while a handle was open on it; it does not pin the directory for later use, and a caller that goes on to ReadDir or Remove through the PATHNAME re-opens the window the check closed. Acting through a retained handle (an *os.Root) is what would close that, and is a different API shape.

Reload staleness

FileIdentity answers "is what I loaded still what is on disk?" from a stat alone, for a reader caching a file another process publishes. The correct form of that test is knowledge about this package's write barrier: mtime equality AND os.SameFile identity, because an in-place writer keeps the inode while moving the mtime, and a publish-by-rename installs a different inode that a restore can hand the OLD timestamp. Either leg alone serves stale content for one of the two write mechanisms; a size comparison misses exactly the same-size replacement. It is a comparison primitive, not a policy — degradation states, stat-error handling, and re-stat cadence stay with the caller.

Confinement

Every write runs through an *os.Root: the *InRoot functions use the caller's root directly, and the absolute-path functions open the target's parent directory as a root and write through it. The absolute-path surface is therefore a thin adapter over one confined write engine.

Confined traversal and removal

An *os.Root confines a path but does not PIN it: a root deliberately follows a symlink component that stays inside its tree, so a multi-component name that is stat-ed and then operated on can address two different files if an ancestor directory is swapped for a symlink in between. Confinement still holds — nothing outside the root is reachable — and inside the tree the operation lands somewhere the caller never inspected.

OpenParentInRoot closes that window: it descends component by component, refusing a symlink and confirming each directory's identity with os.SameFile, and hands back the leaf's own pinned root plus its base name, so the operation that follows names no ancestor at all. RemoveFileInRoot is that descent applied to an unlink, and CleanupStaleTempsInRoot now reclaims every temp through it.

WalkDirInRoot is the traversal counterpart to WriteFileInRoot and ReadBoundedInRoot, for a caller enumerating a tree it does not own: entries stream in fixed ReadDir batches rather than one materialized (and sorted) inventory per directory, exactly one directory handle is open at a time, each directory is opened O_DIRECTORY so a planted FIFO is refused instead of blocking the caller's goroutine, and a symlinked directory is never descended. The callback is an fs.WalkDirFunc and the fs.SkipDir/fs.SkipAll sentinels behave as they do in fs.WalkDir; the two deliberate differences are that entries arrive in directory order (sorted within a batch only) and that a directory's own entries are all visited before the walk descends.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyPath is returned when a path argument is empty.
	ErrEmptyPath = errors.New("atomicfile: empty path")
	// ErrUnsafePath is returned when a path fails the local safety check.
	ErrUnsafePath = errors.New("atomicfile: unsafe path")
	// ErrFileTooLarge is returned when a file exceeds the ReadBounded /
	// ReadBoundedFile size limit, or when content exceeds a WithMaxBytes
	// write cap (there it arrives wrapped, sometimes inside a *WriteError;
	// match with errors.Is).
	ErrFileTooLarge = errors.New("atomicfile: file too large")
	// ErrSymlinkTarget is returned when the target path is a symlink and
	// WithAllowSymlinkTarget was not set.
	ErrSymlinkTarget = errors.New("atomicfile: target is a symlink")
	// ErrNotRegular is returned by ReadBoundedInRoot when the name resolves to
	// something other than a regular file — a directory, named pipe, device node or
	// socket. It is a distinct sentinel because a caller that maps failures onto
	// protocol responses (an HTTP handler answering 400 for a directory but 404 for a
	// missing file) has to tell this case apart from the others; the error text names
	// the actual mode for diagnosis. Match with errors.Is.
	ErrNotRegular = errors.New("atomicfile: not a regular file")
	// ErrNotDirectory is returned by EnsurePrivateDir when the name is occupied by
	// something other than a directory — a plain file, named pipe, device node or
	// socket. It is a distinct sentinel for the reason ErrNotRegular is: a caller
	// deciding what to do next has to tell "somebody planted an object at my
	// directory's name" (fatal, and a signal worth an operator alert) apart from
	// "the directory is there but its mode or owner is wrong", and the error text
	// names the actual type for diagnosis. Match with errors.Is.
	ErrNotDirectory = errors.New("atomicfile: not a directory")
	// ErrNotOwned is returned by EnsurePrivateDir when the directory's owner is not
	// the effective uid, or when its ownership could not be determined at all. It is
	// distinct from a mode failure because the remedy is: a mode can be repaired by
	// whoever owns the path, while a foreign owner can rename or replace the
	// directory AFTER any check returns, so the only safe response is to abandon that
	// path rather than adjust it. Match with errors.Is.
	ErrNotOwned = errors.New("atomicfile: directory not owned by the effective uid")
	// ErrModeTooOpen is returned by EnsurePrivateDir when a PRE-EXISTING directory
	// grants group or other access. It is distinct from ErrModeNotStored because the
	// two say opposite things about who is at fault: this one means the directory is
	// somebody else's and is not private, which this package deliberately refuses to
	// chmod into compliance, while ErrModeNotStored means the filesystem would not
	// store the mode on a directory this process just created. Match with errors.Is.
	ErrModeTooOpen = errors.New("atomicfile: directory mode grants group or other access")
	// ErrModeNotStored is returned by EnforceMode when the mode read back from the
	// handle after the chmod is not the mode that was asked for — an inheritable ACL
	// widening the result, or any filesystem that treats a mode as advisory. It is a
	// distinct sentinel because it is the one failure in this package that is a
	// property of the MOUNT rather than of the path or the caller: retrying, or
	// picking a different name under the same parent, cannot fix it, so a caller that
	// maps failures onto operator guidance has to tell it apart from a permission
	// error. The error text names both the requested and the stored mode. Match with
	// errors.Is.
	ErrModeNotStored = errors.New("atomicfile: filesystem did not store the requested mode")
	// ErrAborted is returned by PendingFile.Commit when the pending file was
	// already aborted by a prior Cleanup. The temp file was removed and nothing
	// reached the final path, so Commit reports this rather than a zero-value
	// Result with a nil error, which would falsely signal success.
	ErrAborted = errors.New("atomicfile: pending file aborted")
)

Sentinel errors.

Functions

func CleanupStaleTemps

func CleanupStaleTemps(dir string, maxAge time.Duration, opts ...Option) (removed int, err error)

CleanupStaleTemps removes temp files in dir that this package created (".atomicfile-<digits>.tmp") and whose mtime is older than maxAge. It returns the number removed. A missing dir is not an error. Best-effort per file: individual stat/remove failures are logged at Debug and skipped (see reapStaleTemp); only a readdir failure is returned.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	// Simulate an orphaned temp left by an interrupted write.
	stale := filepath.Join(dir, ".atomicfile-123456.tmp")
	_ = os.WriteFile(stale, []byte("partial"), 0o644)
	old := time.Now().Add(-2 * time.Hour)
	_ = os.Chtimes(stale, old, old)

	removed, _ := atomicfile.CleanupStaleTemps(dir, time.Hour)
	fmt.Println(removed)
}
Output:
1

func EnforceMode added in v2.8.0

func EnforceMode(f *os.File, want os.FileMode) (os.FileMode, error)

EnforceMode sets want on the OPEN HANDLE f and returns the mode the filesystem actually stored, having already refused a mismatch.

It exists because a mode argument is a REQUEST, not a result, and nothing in the os package says so. mkdir(2) and open(2) take the mode through umask, and a filesystem carrying an inheritable ACL can widen the outcome regardless of what was asked: measured on a ZFS nfs4acl dataset, an inheritable group@:rwx ACE yields 0770 from a 0o700 mkdir, and a child of an already-0700 parent comes back 0770 too, so tightening the parent does not cover it. chmod(2) is the only call that SETS a mode, and a caller that stops there has still only issued a second request. So the sequence is chmod then stat, and the stat is the whole point: it is the only thing that turns "I asked for 0600" into "the file is 0600".

The handle is what makes the verdict sound, for the reason OpenRegular records: observing the pathname a second time to stat it re-opens the window the check exists to close. A path-based chmod-then-stat can chmod one file and certify another if the name is swapped in between, and against a hostile neighbour that is precisely the sequence to attack. Both calls here are fchmod(2) and fstat(2) on the same descriptor, which no rename can redirect. It works for a file or a directory because both are an *os.File.

Only the bits chmod(2) can set are compared — the permission bits plus setuid/setgid/sticky — so the type bits an os.FileMode also carries never make a directory look like a mismatch. That comparison includes setgid on purpose: a directory created under a setgid parent inherits the bit on Linux, which is a real difference between what was asked for and what is on disk.

It is a primitive, not a policy: what to do about a filesystem that refuses the mode stays with the caller. A mismatch returns ErrModeNotStored naming both modes, and the stored mode is returned alongside it so a caller that wants to warn and continue does not have to re-stat to find out what it got. Every other error is the filesystem's own (fchmod or fstat failing), returned unwrapped so errors.Is against fs.ErrPermission works.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "secret.json")
	_ = os.WriteFile(path, []byte(`{}`), 0o644)

	f, _ := os.Open(path)
	defer f.Close()

	// The mode a create or a chmod takes is a REQUEST; the returned mode is what
	// the filesystem stored, read back from the same descriptor that was chmod'ed.
	stored, err := atomicfile.EnforceMode(f, 0o600)
	fmt.Printf("stored %#o, err %v\n", stored, err)
}
Output:
stored 0600, err <nil>

func IsPackageTemp added in v2.5.0

func IsPackageTemp(name string) bool

IsPackageTemp reports whether name is a temp file this package created: ".atomicfile-<digits>.tmp", with a non-empty all-digit middle. It is the exported face of the predicate both sweeps apply (CleanupStaleTemps and CleanupStaleTempsInRoot), so the agreement between a caller's file names and what the sweeps reclaim can be pinned in a test instead of trusted as prose.

The all-digit requirement is the part callers cannot infer. A file that merely shares the prefix and suffix — ".atomicfile-notes.tmp" — is NOT a package temp and no sweep will ever delete it, which is exactly the property that makes the prefix safe to reuse for caller-owned files. Reconstructing the shape with os.CreateTemp(dir, ".atomicfile-*.tmp") happens to satisfy it today only because Go's implementation substitutes decimal digits for "*", which its documentation promises merely to be "a random string": use TempName instead of relying on that, and use this predicate to assert it.

name is a single directory-entry name, not a path — the sweeps match on an entry's final element. Pass filepath.Base(path) if you hold a path.

func OpenParentInRoot added in v2.5.0

func OpenParentInRoot(root *os.Root, name string) (*os.Root, string, error)

OpenParentInRoot opens the parent directory of name as its own *os.Root, pinned to the directory that was inspected, and returns that root together with name's final element.

It exists because *os.Root confines a path but does not pin it. An os.Root deliberately FOLLOWS a symlink component that stays inside the root, so a multi-component name that is stat-ed and then operated on — the ordinary check-then-act any sweep, reaper or cache invalidator performs — can address two different files if an ANCESTOR DIRECTORY is swapped for a symlink in between. The confinement holds (nothing outside the root is reachable), and that is all it promises: inside the tree the operation lands somewhere else than the caller checked. Nothing in the os.Root surface closes that window, because there is no way to say "this component, and only the directory I already looked at".

The descent is what closes it. Each component is Lstat-ed (so a symlink is REFUSED rather than followed), required to be a real directory, opened as its own root, and confirmed with os.SameFile against the directory that was inspected — so a component replaced while it was being opened is refused too. Naming only the returned base through the returned root then removes every ancestor from the operation's path: no in-root symlink can redirect it, and the open handle keeps the directory pinned even if it is renamed afterwards.

Reach for it whenever two operations on one path have to address the same file and the tree is one other writers can modify — a co-mounted Docker volume, a shared NFS export, any directory whose contents are not exclusively yours. A single operation through the caller's own root needs none of this.

The returned root is ALWAYS a fresh handle the caller must close, including for a name that sits directly under root (where it is a second handle on root's own directory), so the close is unconditional and never risks closing the caller's root. The caller owns root; OpenParentInRoot does not close it.

Errors are the filesystem's own, wrapped: a component that has vanished matches fs.ErrNotExist (the benign racing-deletion case a caller usually treats as "already gone"), a component the process may not traverse matches fs.ErrPermission, and a component that is a symlink, a device node or a file — or one that changed identity mid-open — is refused with an error naming the component. name must be relative and must name an entry: "." and ".." are refused with ErrUnsafePath.

func OpenRegular added in v2.6.0

func OpenRegular(path string) (*os.File, os.FileInfo, error)

OpenRegular opens the absolute path read-only and returns the open descriptor together with the FileInfo of that descriptor, refusing a symlink at the final component and anything that is not a regular file. The caller owns the returned file and closes it.

It is the ambient-path sibling of OpenRegularInRoot, for a caller holding a full path into a directory it trusts — its own config or state directory — rather than an *os.Root. The refusals differ because the mechanisms do: O_NOFOLLOW makes the KERNEL refuse a symlink under the name, reported as ErrSymlinkTarget so the read side speaks the write side's vocabulary, where the root-confined form instead lets an in-root symlink resolve (an *os.Root bounds escape but still traverses links inside its tree) and only bounds where it can land. Neither pins the ANCESTOR components: an ambient path resolves them as the filesystem presents them, and a root follows an in-root symlinked directory by design. A caller working in a tree others can write to descends with OpenParentInRoot first and opens the returned base through the pinned root.

This is deliberately NOT how ReadBounded behaves, and does not change it: ReadBounded follows symlinks by design (os.Open resolves them) and stays that way, so a caller wanting the refusal asks for it here.

Errors: ErrEmptyPath or ErrUnsafePath for a path that is empty, holds a NUL, or is not absolute once cleaned (the ValidatePath rule); ErrSymlinkTarget when the kernel refuses the open because the final component is a symlink, with the syscall error kept in the chain; ErrNotRegular for a directory, FIFO, device node or socket, naming the actual mode; and the filesystem's own error otherwise, so a missing file matches fs.ErrNotExist and an unreadable one fs.ErrPermission. ELOOP raised by a symlink loop in an ANCESTOR component is indistinguishable from the final-component refusal at the open boundary and takes the same arm; a caller that must tell the two apart reads the wrapped error.

Example
package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	target := filepath.Join(dir, "state.json")
	_ = os.WriteFile(target, []byte(`{}`), 0o600)
	link := filepath.Join(dir, "state-link.json")
	_ = os.Symlink(target, link)

	f, _, err := atomicfile.OpenRegular(target)
	if err == nil {
		f.Close()
	}
	fmt.Println("regular file:", err)

	// O_NOFOLLOW has the kernel refuse a symlink under the name, so there is no
	// check-then-open window. ReadBounded still follows links by design.
	_, _, err = atomicfile.OpenRegular(link)
	fmt.Println("symlink:", errors.Is(err, atomicfile.ErrSymlinkTarget))
}
Output:
regular file: <nil>
symlink: true

func OpenRegularInRoot added in v2.6.0

func OpenRegularInRoot(root *os.Root, name string) (*os.File, os.FileInfo, error)

OpenRegularInRoot opens name inside root read-only and returns the open descriptor together with the FileInfo of that descriptor, having already refused anything that is not a regular file. The caller owns the returned file and closes it; root stays the caller's too.

It is the open half of ReadBoundedInRoot, which is now built on it, so the two cannot drift: open through the root (a symlink or ".." component in name can never redirect the open outside its tree), non-blocking so a named pipe planted in the tree cannot stall the caller in open(2), then stat the OPEN HANDLE — never the pathname again — and refuse a directory, FIFO, device node or socket with ErrNotRegular. Every consumer that hand-rolls that sequence re-derives the same three non-obvious details, and one of them getting it wrong is a confinement bypass.

The descriptor is what makes it reusable where the bytes are not. A caller STREAMING the file through a decoder or a decryptor never materializes it, so a []byte-returning helper cannot serve it at all; a caller that caches the file and must know when to reload needs the FileInfo the bytes came from, which is what Identify turns into a FileIdentity. Both are the same argument: binding the shape check, the identity and the read to ONE descriptor is the point. Observing the pathname a second time to stat it re-opens the window this closes — a rename in between makes a caller decode one generation's bytes while recording another's identity, and turns every non-regular-file rejection back into a check-then-open race.

For the bytes, hand the descriptor to ReadBoundedFile; that composition IS ReadBoundedInRoot. OpenRegular is the ambient-path sibling.

Errors are the filesystem's own, wrapped only where this package adds a verdict: name must be relative and null-byte-free (ErrEmptyPath / ErrUnsafePath), a missing file or a symlink escaping the root surfaces as the root's own error, and a non-regular file is ErrNotRegular with the actual mode named for diagnosis. There is no context parameter, matching OpenParentInRoot: an open is one syscall, and the caller that goes on to read passes its context there.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	_ = os.WriteFile(filepath.Join(dir, "feed.json"), []byte(`{"items":[]}`), 0o600)

	root, _ := os.OpenRoot(dir)
	defer root.Close()

	// One descriptor carries the shape check, the identity and the bytes. A
	// caller streaming the file (through a decoder, a decryptor) uses f and
	// never materializes it; this one reads it under a cap.
	f, info, err := atomicfile.OpenRegularInRoot(root, "feed.json")
	if err != nil {
		return
	}
	defer f.Close()

	// The FileInfo came from the descriptor the bytes come from, so recording
	// it needs no second stat of the pathname.
	id := atomicfile.Identify(info)
	data, _ := atomicfile.ReadBoundedFile(context.Background(), f, 1<<20)
	fmt.Println(len(data), id.Recorded())
}
Output:
12 true

func ReadBounded

func ReadBounded(ctx context.Context, path string, maxBytes int64) ([]byte, error)

ReadBounded opens path, validates its size against maxBytes, and reads it via an io.LimitReader. Returns ErrFileTooLarge if the file exceeds maxBytes (including if it grows past the limit during the read). ctx is checked before the open and before the read.

Unlike the write primitives, ReadBounded does NOT refuse symlink targets: os.Open follows symlinks, so a symlink at path is resolved and its target is read. Callers reading from a directory writable by a less-trusted principal should confine the path themselves: open the file through an *os.Root and read it with ReadBoundedFile, which applies the same size and context bounds.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "data.txt")
	_ = os.WriteFile(path, []byte("bounded"), 0o644)
	data, _ := atomicfile.ReadBounded(context.Background(), path, 1<<20)
	fmt.Println(string(data))
}
Output:
bounded

func ReadBoundedFile added in v2.1.0

func ReadBoundedFile(ctx context.Context, f *os.File, maxBytes int64) ([]byte, error)

ReadBoundedFile reads up to maxBytes from an already-open file using the same size validation as ReadBounded: it returns ErrFileTooLarge if the file exceeds maxBytes (including if it grows past the limit during the read), and checks ctx before the size stat and before the read. The caller owns f; ReadBoundedFile does not close it.

This is the seam for callers that must open the file themselves before reading it — most importantly, opening through an *os.Root (Go 1.24+) to confine the path to a trusted directory, which ReadBounded cannot do because os.Open follows symlinks. Open the file via the root, then read it here to get the identical bounds and context handling.

func ReadBoundedInRoot added in v2.4.0

func ReadBoundedInRoot(ctx context.Context, root *os.Root, name string, maxBytes int64) ([]byte, error)

ReadBoundedInRoot opens name inside root and reads it under maxBytes, confining the read to root's tree: a symlink or ".." component in name can never redirect the read outside it (Go 1.24+ *os.Root).

It is the read-side counterpart to WriteFileInRoot. Without it, a caller that writes through a confined root has to hand-roll the read half — open through the root, require a regular file, avoid blocking on a FIFO, then delegate to ReadBoundedFile — which is exactly the sequence this package already owns on the write side. Every consumer that hand-rolls it re-derives the same three non-obvious details, and one of them getting it wrong is a confinement bypass.

Only regular files are read. A named pipe, device node or socket planted in the tree is rejected rather than opened, and the open is non-blocking so it cannot stall a caller even momentarily: open(2) on a FIFO with no writer blocks indefinitely, which for a single-goroutine scanner means a permanent hang.

The open half is OpenRegularInRoot and the read half is ReadBoundedFile: this function is exactly their composition, so a caller needing the descriptor itself — to stream the file, or to record its FileInfo as a FileIdentity from the same observation the bytes came from — takes the two apart instead of re-deriving either.

The caller owns root; ReadBoundedInRoot does not close it.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	_ = os.WriteFile(filepath.Join(dir, "cert.pem"), []byte("-----BEGIN..."), 0o600)

	// A root confines every read to this tree: a symlink or ".." in the name cannot
	// redirect the read outside it.
	root, _ := os.OpenRoot(dir)
	defer root.Close()

	data, _ := atomicfile.ReadBoundedInRoot(context.Background(), root, "cert.pem", 1<<20)
	fmt.Println(len(data))
}
Output:
13

func RemoveFileInRoot added in v2.5.0

func RemoveFileInRoot(root *os.Root, name string) error

RemoveFileInRoot removes the regular file at name inside root, unlinking it through a parent directory pinned by OpenParentInRoot so no ancestor component can redirect the removal at another file inside the tree.

It is the removal-side counterpart to WriteFileInRoot: the same name, taken away again, with the same confinement and the ancestor-pinning os.Root itself does not provide (see OpenParentInRoot for why a plain root.Remove of a multi-component name is not the same operation).

Only a regular file is removed. A directory, symlink, device node, socket or named pipe wearing the name is refused with ErrNotRegular and left exactly as found, so a caller sweeping names it believes it wrote cannot be tricked into unlinking something it did not — the same rule ReadBoundedInRoot applies to what it will read. Removing a symlink itself, or an empty directory, is deliberately not this function's job; use the pinned root from OpenParentInRoot for that.

A missing file is reported (matching fs.ErrNotExist) rather than swallowed: whether a name that is already gone is success or a surprise is the caller's judgement.

The caller owns root; RemoveFileInRoot does not close it.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	_ = os.MkdirAll(filepath.Join(dir, "example.com"), 0o750)
	_ = os.WriteFile(filepath.Join(dir, "example.com", "cert.pfx"), []byte("bundle"), 0o600)

	root, _ := os.OpenRoot(dir)
	defer root.Close()

	// The unlink runs through a parent directory pinned component by component, so
	// an ancestor swapped for a symlink cannot redirect it at another file in the
	// tree — which a plain root.Remove of this same name would allow.
	err := atomicfile.RemoveFileInRoot(root, "example.com/cert.pfx")
	_, statErr := os.Lstat(filepath.Join(dir, "example.com", "cert.pfx"))
	fmt.Println(err, os.IsNotExist(statErr))
}
Output:
<nil> true

func TempName added in v2.5.0

func TempName() string

TempName returns a fresh temp base name of the exact shape this package creates and IsPackageTemp recognises, drawn from crypto/rand.

It exists so a caller that has to create a file of its own in a directory this package sweeps — a writability probe, a test fixture standing in for an interrupted write — gets a name the sweep reclaims without rebuilding a convention the package owns. The name is only a name: nothing is created, and two calls can be used for two files.

A collision with an existing file is possible in principle (the middle is a 64-bit draw) and not handled here, because a caller creating the file with O_EXCL learns about it and can simply ask again — the way createTempInRoot does internally.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)

	// A caller staging its own file in a directory this package sweeps takes
	// the name from TempName instead of rebuilding the convention, so an
	// orphan is reclaimed like any other temp.
	path := filepath.Join(dir, atomicfile.TempName())
	_ = os.WriteFile(path, []byte("mine"), 0o600)
	old := time.Now().Add(-2 * time.Hour)
	_ = os.Chtimes(path, old, old)

	removed, _ := atomicfile.CleanupStaleTemps(dir, time.Hour)
	fmt.Println(atomicfile.IsPackageTemp(filepath.Base(path)), removed)
}
Output:
true 1

func ValidatePath added in v2.7.0

func ValidatePath(path string) error

ValidatePath checks path against the rule this package's absolute-path entry points apply — WriteFile, WriteReader, NewPendingFile, ReadBounded — returning nil when the path is acceptable to them, and otherwise the very error they would return: ErrEmptyPath for an empty path, ErrUnsafePath for a path holding a NUL byte or one that is not absolute once cleaned. It is the exported face of validateAbsClean, which stays the single implementation, so an acceptance decided here and the rejection a later write applies cannot drift apart.

It exists for the acceptance check that happens long before the write — a config path validated at startup, a CLI flag refused with a usage message, a request field answered with a 400. filepath.IsAbs is the usual stand-in and is NOT the same rule: it accepts a path with an embedded NUL ("/tmp/a\x00b" is absolute), which every write here refuses, so a caller validating with IsAbs admits input its own write path rejects later, at a point far from where the value came in. It also answers a bool, leaving the caller to invent the two reasons this package already distinguishes.

Nothing on the filesystem is consulted: no stat, no open, no temp file. The path need not exist, its parent need not be a directory, and the call is cheap enough for a hot loop. That also bounds what nil means — the path is well formed, NOT that a write there will succeed. ProbeWritable answers that second question, and answers it by actually writing.

Being absolute is not containment. filepath.Clean normalizes ".." in an absolute path, so nil says nothing about which subtree the path lands in; a caller confining writes to a directory tree uses the *os.Root-backed APIs (WriteFileInRoot / WriteReaderInRoot).

func WalkDirInRoot added in v2.5.0

func WalkDirInRoot(ctx context.Context, root *os.Root, fn fs.WalkDirFunc) error

WalkDirInRoot enumerates root's tree and hands every entry to fn, root-relative, confining the traversal to root's tree: every step is an openat-relative syscall, no ambient path is ever constructed, and a symlinked directory is never descended.

It is the traversal counterpart to WriteFileInRoot and ReadBoundedInRoot. Without it, a caller that writes and reads through a confined root has to hand-roll the enumeration half — fs.WalkDir over root.FS(), or its own ReadDir loop — and both spellings re-derive the same three non-obvious details:

  • Memory. fs.WalkDir materializes and sorts each directory's whole inventory before the first callback, so a hostile or merely large directory is already resident by the time the caller could refuse it. This reads in fixed batches (walkReadDirBatch) and calls back on each one.
  • Descriptors. Exactly ONE directory handle is open at a time: a directory's own entries are all visited, and its handle closed, before any subdirectory of it is opened. What the walk carries between directories is a queue of NAMES, which cannot exhaust the process's descriptors on a deep tree.
  • Occupants. Each directory is opened O_DIRECTORY, so a named pipe swapped in for a directory between the readdir that classified it and this open is REFUSED with ENOTDIR instead of blocking: open(2) on a FIFO with no writer blocks indefinitely, which for a single-goroutine sweep is a permanent hang. It is the same guarantee ReadBoundedInRoot gives every file it opens; this is the directory half.

Callback contract

fn is an fs.WalkDirFunc and is called exactly as fs.WalkDir calls one: the root itself first as ".", then each entry pre-order, with a directory that cannot be opened or finished reported through fn for ITS OWN path (d nil, err set). The fs.SkipDir and fs.SkipAll sentinels mean what they mean in fs.WalkDir — SkipDir on a directory skips its contents, SkipDir on a non-directory skips the rest of the containing directory, SkipAll ends the walk without an error — and any other error from fn ends the walk and is returned. Whether a read failure below the root is fatal is likewise the callback's call: return the error to abort, or nil to count an unreadable sub-path and carry on with the rest of the tree.

Two deliberate differences from fs.WalkDir

Entries arrive in DIRECTORY order, sorted only within a batch, because a global sort is exactly the materialization this avoids. Do not build a decision on the order; a caller that needs a total order sorts what it collected. And a directory's own entries are all visited before the walk descends into its subdirectories, which is what buys the single-descriptor property above.

Cancellation

The walk stops between batches once ctx is done, and an already-cancelled context does no work, so a walk of a large tree cannot hold up shutdown. That bound is at most one batch of entries; a caller that wants per-entry cancellation checks ctx in fn, which every visitor already positioned to abort on shutdown does anyway.

The caller owns root; WalkDirInRoot does not close it. Pass root.OpenRoot(sub) to walk a subtree.

Example
package main

import (
	"context"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	_ = os.MkdirAll(filepath.Join(dir, "example.com"), 0o750)
	_ = os.WriteFile(filepath.Join(dir, "example.com", "cert.pfx"), []byte("bundle"), 0o600)
	// A symlinked directory is reported and never descended, so nothing is
	// enumerated under a path whose ancestors do not physically hold it.
	_ = os.Symlink("example.com", filepath.Join(dir, "alias"))

	root, _ := os.OpenRoot(dir)
	defer root.Close()

	var found []string
	_ = atomicfile.WalkDirInRoot(context.Background(), root, func(rel string, d fs.DirEntry, err error) error {
		if err != nil {
			// A sub-path the walk cannot enter: count it and carry on with the
			// rest of the tree, or return the error to abort.
			return nil
		}
		if !d.IsDir() && strings.HasSuffix(rel, ".pfx") {
			found = append(found, rel)
		}
		return nil
	})
	fmt.Println(found)
}
Output:
[example.com/cert.pfx]

Types

type FileIdentity added in v2.4.0

type FileIdentity struct {
	// contains filtered or unexported fields
}

FileIdentity records WHICH generation of a file a reader currently holds, so a cache can answer "is what I loaded still what is on disk?" from a stat alone, without re-reading the bytes.

The correct form of that test is knowledge about this package's own write barrier, which is why it lives here. Two different write mechanisms can change a file's content, and each defeats one half of the naive check:

  • An IN-PLACE writer (a plain os.WriteFile, an editor, a truncate-and-write) keeps the same inode and moves the mtime forward. Comparing identity alone would call that unchanged.
  • A PUBLISH-BY-RENAME writer — every write in this package — installs a DIFFERENT inode. Normally its mtime differs too, but it need not: a backup restore, an rsync with -t, a tar extract with -p, or any re-publication of an archived generation lands new content carrying the OLD timestamp. Comparing mtime alone would call that unchanged, and the stale copy would then be served until something else happened to touch the file.

So the test is mtime equality AND os.SameFile identity, and both legs are load-bearing. Size is not part of it: a same-size replacement is exactly the case a size comparison misses, and a differing size is already covered by one of the two legs.

The zero value records nothing, which reports Changed — the fail direction a cache wants, since a spurious reload costs one read while a missed reload serves stale data indefinitely.

FileIdentity retains the os.FileInfo it was given. It is a comparison primitive, not a policy: what to do about a changed file, whether a stat error is fatal, and when to re-stat at all stay with the caller.

func Identify added in v2.4.0

func Identify(info os.FileInfo) FileIdentity

Identify captures the identity of the file described by info, as returned by os.Stat, os.Lstat, or (*os.File).Stat. A nil info records nothing, so the result reports Changed against every later stat.

func (FileIdentity) Changed added in v2.4.0

func (id FileIdentity) Changed(info os.FileInfo) bool

Changed is the negation of Matches, for the reload-side reading: it reports whether info is a file generation this identity did not capture, and so whether a reader holding the captured generation must load again.

func (FileIdentity) Matches added in v2.4.0

func (id FileIdentity) Matches(info os.FileInfo) bool

Matches reports whether info describes the same file generation this identity captured: an equal modification time AND the same file (os.SameFile, which compares the underlying device and inode). An unrecorded identity matches nothing, and a nil info — no file observed — matches nothing.

func (FileIdentity) ModTime added in v2.4.0

func (id FileIdentity) ModTime() time.Time

ModTime returns the captured modification time, or the zero Time when nothing was recorded. It is exposed for diagnostics — a log line or an assertion naming which generation is held — not for the freshness test, which Matches owns because the mtime alone is not sufficient.

func (FileIdentity) Recorded added in v2.4.0

func (id FileIdentity) Recorded() bool

Recorded reports whether an identity was captured at all. A zero FileIdentity (nothing loaded yet, or a load that failed before its stat) records nothing.

type Option

type Option func(*cfg)

Option configures an atomic write operation.

func WithAllowSymlinkTarget

func WithAllowSymlinkTarget() Option

WithAllowSymlinkTarget permits writing to a path that is currently a symlink. By default symlink targets are refused with ErrSymlinkTarget. Note the atomic rename REPLACES the symlink with a regular file; it does not write through to the link's target. Resolve with filepath.EvalSymlinks first if that is the intent.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets a custom logger. If not provided, slog.Default() is used.

func WithMaxBytes added in v2.3.0

func WithMaxBytes(n int64) Option

WithMaxBytes caps the content size an atomic write will stage, the write-side mirror of ReadBounded's bound: a writer that also owns the reader can refuse to persist a file its own read path would refuse to load, instead of silently writing something that fails open on the next read. WriteFile and WriteFileInRoot reject over-cap content before the temp file is created; WriteReader and WriteReaderInRoot reject the copy chunk that would cross the cap; a PendingFile rejects the Write/WriteString/ReadFrom call that would cross it, whole, so the staged temp never holds an over-cap prefix (see PendingFile.Write). The barrier additionally verifies the staged file's actual size before publication, so bytes staged outside those interfaces (WriteAt, Write after Seek, a reopen of the temp by path) cannot publish an over-cap file. Every rejection matches ErrFileTooLarge and leaves the previous file at the target path intact. n <= 0 means no cap (the default).

func WithMkdirMode

func WithMkdirMode(mode os.FileMode) Option

WithMkdirMode creates the parent directory (and any missing ancestors) with the given permission before writing. Without it, a missing parent directory is an error.

func WithMode

func WithMode(mode os.FileMode) Option

WithMode sets the permission applied to the written file. Defaults to 0o644.

func WithNoSync

func WithNoSync() Option

WithNoSync skips the fsync on both the temp file and the parent directory, providing atomicity without durability. Result.Durable is then always false.

func WithPreserveMode

func WithPreserveMode() Option

WithPreserveMode stats the target before writing and applies its existing mode to the new file, falling back to the WithMode value if the target does not exist or cannot be stat-ed (a non-ErrNotExist stat failure is logged at Warn).

func WithPreserveOwnership

func WithPreserveOwnership() Option

WithPreserveOwnership stats the target before writing and chowns the temp file to match the target's uid/gid. Requires CAP_CHOWN or root; a no-op when the target does not exist, cannot be stat-ed, or off Unix (a non-ErrNotExist stat failure is logged at Warn). Best-effort: the chown runs after the temp-file fsync, so unlike content and mode it is not crash-covered. A chown failure is logged at Warn and does not fail the write (the file lands with the writer's ownership).

func WithRecursive added in v2.4.0

func WithRecursive() Option

WithRecursive makes a stale-temp sweep descend into subdirectories. It affects CleanupStaleTemps and CleanupStaleTempsInRoot and is ignored by every write entry point.

Off by default, and the default is the interesting half: a sweep is a DESTRUCTIVE operation, so how much of the filesystem it touches must be stated at the call site rather than inferred from which function was reached for. Both sweeps therefore behave identically without it — one directory, no descent — and depth is opt-in.

Reach for it when temps can be staged below the directory you name. That happens whenever the caller's own output tree is nested, because a temp is always created in the SAME directory as its final target: a write to out/example.com/cert.pfx leaves its orphan in out/example.com, which a flat sweep of out/ never sees. A caller with a flat cache directory does not need it and should not pass it.

func WithRepairOwnedDir added in v2.9.0

func WithRepairOwnedDir() Option

WithRepairOwnedDir lets EnsurePrivateDir repair a PRE-EXISTING directory's mode instead of refusing it with ErrModeTooOpen. It affects EnsurePrivateDir only and is ignored by every write entry point.

It exists for the caller whose directory is its OWN past output. An app that created <root>/<key>/ at 0700 on a filesystem that stored 0770 will, on the next release, meet its own directory and be refused by the default rule — which is how a mode fix turns into an outage on upgrade, with every item failing at a directory the app itself made.

Repairing such a directory is sound, and the reason is ownership rather than trust: mkdir(2) gives a new directory to its creator, a directory cannot be the target of a hard link, and the open is O_NOFOLLOW at the final component — so a directory that fstats as owned by the effective uid was made by this uid, not planted by a neighbour who merely writes the parent. EnsurePrivateDir has already established exactly that before this option is consulted, and every other refusal (ErrNotOwned, ErrNotDirectory, the symlink refusal) still fires first and is unaffected.

It is deliberately NOT the default, because a wide mode on a directory you own can be a DELIBERATE choice rather than drift. seadex-scout's report directory is intentionally left wider so an operator can read reports out of it; a library that quietly narrowed it would break that on a version bump. Refusing keeps the default honest — the caller has to say "this directory is mine and its privacy is not negotiable" — and Repaired reports when the option actually changed something, so an app can log the one-time repair rather than discover it later.

type PendingFile

type PendingFile struct {
	*os.File
	// contains filtered or unexported fields
}

PendingFile is a temp file open for writing, destined to atomically replace a target on Commit. It embeds *os.File, so callers get the full io.Writer/io.ReaderFrom/fmt.Fprintf surface, and the embedded Name() reports the temp's path (root.Name() joined with the temp name — absolute for NewPendingFile), so the staged file can be handed to external verifiers before Commit. The configuration is captured at construction and reused at Commit, so durability options cannot drift between the two calls.

A PendingFile is written as an append-only stream: Write, WriteString, and ReadFrom maintain a byte count (BytesWritten) that Truncate re-syncs, and a WithMaxBytes cap is enforced on exactly that stream. Operations on the embedded *os.File that step outside the stream model (WriteAt, Write after Seek) bypass the accounting, but not the cap: Commit re-verifies the staged file's actual size against the cap at the durability barrier and refuses to publish an over-cap file (the error matches ErrFileTooLarge).

Every filesystem operation (temp creation, rename, parent-dir fsync, removal) runs through an *os.Root: the caller's root for NewPendingFileInRoot, or a root of the target's parent directory that NewPendingFile opens and owns. An owned root is closed when the PendingFile reaches a terminal state (Commit called, or Cleanup succeeded); an abandoned PendingFile therefore holds two file descriptors (temp + root) until then, just as it holds its temp file on disk.

A PendingFile is not safe for concurrent use: Commit and Cleanup mutate unsynchronized lifecycle state (state, result, err). Confine each PendingFile to a single goroutine. The package-level WriteFile, WriteReader, ReadBounded, and CleanupStaleTemps are stateless and safe to call concurrently on distinct paths.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "pending.txt")
	pf, _ := atomicfile.NewPendingFile(context.Background(), path)
	defer func() { _ = pf.Cleanup() }()
	_, _ = pf.Write([]byte("incremental"))
	_, _ = pf.Commit(context.Background())
	data, _ := os.ReadFile(path)
	fmt.Println(string(data))
}
Output:
incremental

func NewPendingFile

func NewPendingFile(ctx context.Context, path string, opts ...Option) (*PendingFile, error)

NewPendingFile creates a temp file destined to atomically replace path. Write to it, then call Commit to finalize or Cleanup to abort. Mode defaults to 0o644 (override with WithMode). ctx is checked before the temp is created.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "pending.txt")
	pf, _ := atomicfile.NewPendingFile(context.Background(), path)
	defer func() { _ = pf.Cleanup() }()
	_, _ = pf.Write([]byte("incremental"))
	res, _ := pf.Commit(context.Background())
	data, _ := os.ReadFile(res.Path)
	fmt.Println(string(data))
}
Output:
incremental

func NewPendingFileInRoot added in v2.2.0

func NewPendingFileInRoot(ctx context.Context, root *os.Root, name string, opts ...Option) (*PendingFile, error)

NewPendingFileInRoot creates a temp file destined to atomically replace name, a path relative to root, with the same confinement as WriteFileInRoot: every filesystem operation (temp creation, rename, parent-dir fsync, removal) runs through the *os.Root, so a symlink or ".." component in name can never touch anything outside root's tree. Write to the returned PendingFile, then call Commit to finalize or Cleanup to abort; the lifecycle (idempotent Commit, ErrAborted after Cleanup, retryable failed Cleanup) is identical to NewPendingFile. Mode defaults to 0o644 (override with WithMode). ctx is checked before the temp is created. A nil root returns ErrUnsafePath.

The caller owns root and must keep it open for the PendingFile's lifetime (through Commit or Cleanup); the PendingFile never closes a caller-provided root. Result.Path is root's directory joined with the cleaned relative name.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	root, _ := os.OpenRoot(dir)
	defer func() { _ = root.Close() }()
	// The pending temp and its eventual rename are confined to the root's
	// tree; the caller keeps ownership of the root.
	pf, _ := atomicfile.NewPendingFileInRoot(context.Background(), root, "staged.txt")
	defer func() { _ = pf.Cleanup() }()
	_, _ = pf.Write([]byte("confined incremental"))
	res, _ := pf.Commit(context.Background())
	data, _ := os.ReadFile(res.Path)
	fmt.Println(string(data))
}
Output:
confined incremental

func (*PendingFile) BytesWritten added in v2.3.0

func (p *PendingFile) BytesWritten() int64

BytesWritten reports the staged file's size under the append-stream model: bytes accepted through Write, WriteString, and ReadFrom, re-synced by Truncate. Operations on the embedded *os.File that step outside the stream model (WriteAt, Write after Seek) are not tracked; a WithMaxBytes cap still catches them at Commit, which verifies the staged file's actual size.

func (*PendingFile) Cleanup

func (p *PendingFile) Cleanup() error

Cleanup closes and removes the temp file, aborting the pending write. It is a no-op once Commit has been called — a successful Commit already moved the data into place, and a failed Commit already removed the temp. After a successful Cleanup, a subsequent Commit returns ErrAborted.

If the temp removal fails (for a reason other than the file already being gone), Cleanup returns that error WITHOUT marking the write cleaned, so a later Cleanup retries the removal — a failed Cleanup never falsely reports the temp gone, and a subsequent Commit still returns ErrAborted. Repeated Cleanup calls are therefore a no-op after success but a retry after a removal failure. Safe to defer immediately after NewPendingFile.

func (*PendingFile) Commit

func (p *PendingFile) Commit(ctx context.Context) (Result, error)

Commit runs the durability barrier (WithMaxBytes size verification, chmod, optional fsync, close), applies ownership, atomically renames the temp into place, and fsyncs the parent directory. With a WithMaxBytes cap set, the staged file's actual size is measured (fstat) and an over-cap file fails Commit with an error matching ErrFileTooLarge — bytes staged outside the append-stream model cannot publish. Commit is idempotent: repeated calls return the first result. Calling Commit after Cleanup returns ErrAborted — the temp was already removed, so there is nothing to commit, and a nil error would falsely signal that the data reached its final path. After a successful Commit, Cleanup is a no-op. ctx is checked through the temp-side barrier (before chmod, around the fsync, and before close); a context cancelled at or before close aborts and removes the temp. Once the barrier passes, ownership and the rename run without a further ctx check, so a context cancelled in the narrow window between close and rename still commits.

func (*PendingFile) ReadFrom added in v2.3.0

func (p *PendingFile) ReadFrom(r io.Reader) (int64, error)

ReadFrom streams r into the staged temp. With a WithMaxBytes cap set it routes every chunk through Write, so the cap and accounting hold; uncapped it delegates to the embedded *os.File's ReadFrom (keeping the OS copy fast path) and records the copied size.

func (*PendingFile) Truncate added in v2.3.0

func (p *PendingFile) Truncate(size int64) error

Truncate resizes the staged temp and re-syncs the byte accounting to the new size, keeping the append-stream model coherent for callers that trim a trailing byte after encoding (e.g. dropping json.Encoder's newline before Commit). Growing the file beyond a WithMaxBytes cap is rejected with an error matching ErrFileTooLarge.

func (*PendingFile) Write added in v2.3.0

func (p *PendingFile) Write(b []byte) (int, error)

Write stages p, enforcing the WithMaxBytes cap when one is set: a write that would cross the cap is rejected whole - no byte of it reaches the temp - with an error matching ErrFileTooLarge, so the staged content never holds an over-cap prefix and a later Commit cannot publish an over-cap file. Accepted bytes advance BytesWritten.

func (*PendingFile) WriteString added in v2.3.0

func (p *PendingFile) WriteString(s string) (int, error)

WriteString applies the same WithMaxBytes cap and byte accounting as Write (the embedded *os.File's own WriteString would bypass both), so io.WriteString and friends stay inside the stream model.

type PrivateDir added in v2.8.0

type PrivateDir struct {
	// Mode is the mode the filesystem actually stored, as read back from the
	// open handle: the permission bits plus setuid/setgid/sticky, without the
	// type bits. When the error is nil this is always privateDirMode, except on
	// the pre-existing-and-already-private path, where it is what was found.
	Mode os.FileMode
	// Created reports whether THIS call created the directory. It is the field
	// the repair decision turns on (see EnsurePrivateDir): a directory this
	// process just made is one no other writer has ever held a name to, and a
	// pre-existing one belongs to whoever made it.
	Created bool
	// Repaired reports whether the mode had to be corrected because the
	// filesystem did not store what it was asked for — an inheritable ACL
	// widening a fresh 0700 directory. On a Created directory that repair is
	// unconditional; on a pre-existing one it happens only under
	// WithRepairOwnedDir, so Repaired without Created means the option was set
	// AND it changed something. Either way it is worth logging: it says the
	// filesystem under this path does not honour mode requests, which every
	// other mkdir in the program is also subject to.
	Repaired bool
}

PrivateDir reports the outcome of one EnsurePrivateDir call: what happened to the directory, and what the filesystem actually stored for it.

It is only meaningful alongside a nil error. A non-nil error means no verdict was reached, which is NOT the same as "nothing happened" — the mkdir may have succeeded and a later step refused the result, so the directory can exist while its custody is unestablished. Treat the failure as fatal for the purpose the directory was for; do not retry into it.

func EnsurePrivateDir added in v2.8.0

func EnsurePrivateDir(dir string, opts ...Option) (PrivateDir, error)

EnsurePrivateDir establishes custody of ONE directory level that only this process's user may enter: it creates dir 0700 if absent, then proves from an open handle that what is now at that path is a real directory, owned by the effective uid, with no group or other access.

It is the composition callers keep hand-rolling. Two apps in this fleet establish custody of a private directory inside a parent other users can write — a state directory under /tmp, an admin-socket directory — and their copies have already DRIFTED on the mode question: one learned that mkdir's mode is a request and added a chmod plus a re-stat of the levels it created, the other never did, so all four of its checks run only on the already-exists path and its own fresh mkdir returns success having verified nothing. That is the bug this exists to delete: a custody directory born group-writable, by a call that reported success, and never looked at again.

One level, deliberately

dir's own parent is not created, inspected, or vouched for. A multi-level path is a loop over the levels, outermost first, because each level needs the same verdict and the caller is the only one who knows which levels are its own — the one existing consumer that does this already loops. os.MkdirAll cannot substitute for either half: it stats the path, FOLLOWS a symlink, finds a directory and returns nil, so it cannot tell "I created this" from "something was already here", which is the distinction every decision below turns on.

The sequence, and why each step is there

  1. mkdir(2) at 0700, recording whether THIS call created the level. An fs.ErrExist means it did not; any other error is returned as the filesystem gave it.
  2. Open the result O_DIRECTORY|O_NOFOLLOW|O_RDONLY. O_NOFOLLOW makes the KERNEL refuse a symlink planted at the final component rather than following it, which no check-then-open sequence can do without a race; O_DIRECTORY refuses anything that is not a directory and is also what stops a planted FIFO stalling the caller indefinitely in open(2) with no writer on the other end. Which of the two refusals fired is reported as ErrSymlinkTarget or ErrNotDirectory; because the flags collapse a final-component symlink onto ENOTDIR, telling them apart costs one Lstat of the already-refused name, used to label the error and nothing else (see refusedOccupant).
  3. fstat(2) the handle. Everything after this reads the descriptor, never the pathname, so no rename between two observations can make the verdict describe a different object than the one inspected.
  4. Require the owner uid to equal os.Geteuid(). This is ownership, not just mode, and it is the check most easily left out: a level somebody else owns is one they can rename or replace AFTER the verdict returns — including with a symlink the caller then follows — so a perfectly-moded 0700 directory owned by another uid passes every other check here and still leaves the planted-path attack reachable.
  5. If this call CREATED the level, EnforceMode it to 0700. This is the ACL-widening repair, and it is safe precisely BECAUSE we made it: mkdir reported the path as ours, so no other writer has ever held a name there to swap in, and the chmod cannot be tightening someone else's directory.
  6. If the level PRE-EXISTED, it is never chmod'ed — repairing a directory another principal made is not this primitive's call, and taking over the name would hand them whatever gets written under it. It is instead REFUSED when any group or other bit is set (ErrModeTooOpen), which is what keeps the refusal firing on exactly the planted shape the check is for.

The verdict is POINT-IN-TIME, and this is the limit to read carefully

It proves what was true of one inode while a handle was open on it. It does NOT pin the directory for the caller's later use, and nothing here can: the handle is closed before the call returns, and a caller that then does a ReadDir, a Remove, an Open or a Mkdir through the PATHNAME re-resolves every component and re-opens the window this closed. Where the parent is writable by others, the honest reading is that the verdict covers the moment of the check and the caller's own subsequent operations are unprotected by it.

What would close that gap is acting through a retained handle instead of a name — the openat(2)-relative operations of an *os.Root (see OpenParentInRoot for the same argument about ancestor components) — which is a different API shape: the caller would hold the directory open for its whole lifetime and name only leaves inside it. Neither current consumer needs that: one seeds a directory whose entries are unguessable handles, the other creates a socket directory once at startup. If a consumer ever does, the fix is a root-returning sibling of this function, not more checks in it.

Errors

ErrEmptyPath or ErrUnsafePath when dir is empty, holds a NUL, or is not absolute once cleaned (the ValidatePath rule; a relative dir would make the verdict a statement about the process's current directory, which another goroutine can change while this runs). ErrSymlinkTarget for a symlink at the final component, ErrNotDirectory for a plain file, FIFO, device node or socket, ErrNotOwned for a foreign owner, ErrModeTooOpen for a pre-existing directory with group or other access, ErrModeNotStored when the filesystem refuses to store 0700 on a directory this call created. Everything else is the filesystem's own error, so a permission failure matches fs.ErrPermission. Match with errors.Is.

Of the functional options only WithLogger is consulted, for the one Warn line a mode repair emits; every other Option is ignored (the mode is not a parameter — a "private directory" with a caller-chosen mode is a different primitive, and this one's whole contract is 0700).

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	base, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(base)

	// One call establishes ONE level, so a multi-level path is the caller's loop,
	// outermost first: each level gets its own verdict.
	root := filepath.Join(base, "app")
	state := filepath.Join(root, "state")
	for _, dir := range []string{root, state} {
		pd, err := atomicfile.EnsurePrivateDir(dir)
		if err != nil {
			fmt.Println("refused:", err)
			return
		}
		fmt.Printf("%s created=%t mode=%#o\n", filepath.Base(dir), pd.Created, pd.Mode)
	}

	// A second run adopts what the first one left, and never chmods it.
	pd, _ := atomicfile.EnsurePrivateDir(state)
	fmt.Printf("second run created=%t mode=%#o\n", pd.Created, pd.Mode)
}
Output:
app created=true mode=0700
state created=true mode=0700
second run created=false mode=0700
Example (Refusals)
package main

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	base, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(base)

	// A symlink planted at the name is refused by the kernel, not followed.
	link := filepath.Join(base, "link")
	_ = os.Symlink(base, link)
	_, err := atomicfile.EnsurePrivateDir(link)
	fmt.Println("symlink:", errors.Is(err, atomicfile.ErrSymlinkTarget))

	// A pre-existing directory somebody else could enter is refused, never
	// repaired: chmod'ing another principal's directory would take over its name.
	shared := filepath.Join(base, "shared")
	_ = os.Mkdir(shared, 0o755)
	_ = os.Chmod(shared, 0o755)
	_, err = atomicfile.EnsurePrivateDir(shared)
	fmt.Println("group/other access:", errors.Is(err, atomicfile.ErrModeTooOpen))
}
Output:
symlink: true
group/other access: true

type ProbeResult added in v2.5.0

type ProbeResult struct {
	// Err is the failure from Stage, unwrapped to the underlying filesystem
	// error so errors.Is against fs.ErrPermission, fs.ErrNotExist or
	// syscall.ENOSPC works. It is nil exactly when OK reports true.
	Err error
	// Dir is the directory that was probed: the cleaned argument for
	// ProbeWritable, or root.Name() joined with the cleaned relative name for
	// ProbeWritableInRoot (the Result.Path convention).
	Dir string
	// Name is the probe file's base name once it was created, and "" when the
	// probe never got that far. It always satisfies IsPackageTemp, so a
	// leftover is reclaimable by CleanupStaleTemps.
	Name string
	// Stage is the first stage that failed, or ProbeStageNone when all passed.
	Stage ProbeStage
	// Leaked reports whether the probe file is still on disk. It can be true
	// only alongside ProbeStageRemove, or alongside ProbeStageWrite,
	// ProbeStageSync or ProbeStageClose when the follow-up unlink also failed
	// (that secondary error is logged at Debug, since Err holds the first and
	// more informative failure).
	Leaked bool
}

ProbeResult reports the outcome of one directory writability probe.

It is an outcome record, not an error: a stage failure arrives here, never as the probe function's error return, so the caller decides which stages are fatal, which deserve a warning, and how to word each one. A caller that wants the whole thing to be pass/fail asks OK once.

func ProbeWritable added in v2.5.0

func ProbeWritable(ctx context.Context, dir string, opts ...Option) (ProbeResult, error)

ProbeWritable proves dir is genuinely writable by the running process, by doing what a real atomic write does — create a temp file, write and flush a byte, close it, unlink it — and reporting which stage failed.

Reach for it in a preflight, where the alternative is a stat of the mode bits, and those lie: an NFS or FUSE mount, a read-only bind mount, and a Docker volume owned by another UID can all present a writable-looking directory that refuses the first write. A hand-rolled create-close-remove probe is the usual answer and the usual bug too, because the close and the unlink are the errors callers discard — a directory that accepts a create and refuses cleanup then passes a preflight silently, and its leftover file is named nothing anyone sweeps.

Nothing about policy is decided here. Every filesystem outcome, including a total refusal, is reported in the ProbeResult; the error return is non-nil only when the probe could not be attempted at all (an empty dir, or a context already done), so `err != nil` never means "not writable". See ProbeStage for the ladder and ProbeResult.Writable for the usual warn-versus-fail split.

The probe file carries this package's own temp-name shape (see TempName), so a leftover from a crash — or from a directory that denies the unlink — is reclaimed by CleanupStaleTemps like any other orphaned temp, by construction rather than by a naming convention the caller has to reproduce.

A missing dir fails at ProbeStageCreate; pass WithMkdirMode to create it first and get ProbeStageMkdir instead. WithNoSync skips the flush stage. dir may be relative, matching CleanupStaleTemps' dir argument rather than the write functions' absolute-path contract.

ctx is checked once, before anything is created. The stages are single filesystem calls the OS does not make interruptible, and a probe that has begun always runs its own cleanup rather than abandoning a file, so a caller guarding against a wedged mount needs its own timeout around the call.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)

	res, err := atomicfile.ProbeWritable(context.Background(), dir)
	if err != nil {
		return // the probe could not be attempted (empty dir, cancelled ctx)
	}
	// The stage decides the policy, not the library: this caller refuses to
	// start when the directory cannot take a write, and only warns when the
	// write worked but the probe file could not be cleaned up.
	switch {
	case !res.Writable():
		fmt.Println("not writable:", res.Stage, res.Err)
	case !res.OK():
		fmt.Println("writable, but cleanup failed:", res.Stage, "leaked:", res.Leaked)
	default:
		fmt.Println("writable, nothing left behind")
	}
	// The probe file carries this package's temp shape, so a leaked one is
	// reclaimed by CleanupStaleTemps.
	fmt.Println(atomicfile.IsPackageTemp(res.Name))
}
Output:
writable, nothing left behind
true

func ProbeWritableInRoot added in v2.5.0

func ProbeWritableInRoot(ctx context.Context, root *os.Root, name string, opts ...Option) (ProbeResult, error)

ProbeWritableInRoot is ProbeWritable confined to root's tree: name is the directory to probe relative to root ("." for root itself), and every filesystem operation runs through the *os.Root, so a symlink or ".." component can never let the probe create or unlink anything outside it. An escaping name is refused by the root and reported as ProbeStageCreate (or ProbeStageMkdir under WithMkdirMode), the same way a root-confined write surfaces it.

It is the twin for a caller that already holds a root over the directory it is about to write to: probing through that handle checks the same object the writes will use, instead of re-resolving the path and probing whatever it resolves to this time.

Outcome model, options, cancellation and reclaimability are identical to ProbeWritable, including the rule that a stage failure is never returned as an error. The caller owns root; ProbeWritableInRoot does not close it. A nil root returns ErrUnsafePath.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	root, _ := os.OpenRoot(dir)
	defer func() { _ = root.Close() }()

	// Probing through the root a caller already holds checks the same object
	// its writes will use; "." is the root itself.
	res, _ := atomicfile.ProbeWritableInRoot(context.Background(), root, ".")
	fmt.Println(res.OK(), res.Leaked)

	// An escaping name is refused by the root, reported as a stage failure.
	escaped, _ := atomicfile.ProbeWritableInRoot(context.Background(), root, "../outside")
	fmt.Println(escaped.Stage, escaped.Writable())
}
Output:
true false
create probe file false

func (ProbeResult) OK added in v2.5.0

func (r ProbeResult) OK() bool

OK reports whether every stage passed, which is the only outcome that proves the directory usable end to end.

func (ProbeResult) Writable added in v2.5.0

func (r ProbeResult) Writable() bool

Writable reports whether the directory accepted a real write: the probe file was created, written and flushed, so at worst only teardown (close, unlink) failed. It is the split a caller needs to warn about a leftover while still treating the directory as usable, without hard-coding the stage order at the call site.

Under WithNoSync the bytes were written but not flushed, so this reports what the caller asked to be checked, no more.

type ProbeStage added in v2.5.0

type ProbeStage int

ProbeStage identifies which step of a writability probe failed. The stages are the whole ladder a real write walks, in order, because a directory can fail any one of them alone: a filesystem can accept the directory entry yet reject the first data write, surface a delayed failure only at Sync or Close, or accept everything and deny the unlink.

The order is load-bearing, and it is what lets a caller pick its own policy (see ProbeResult.Writable): a failure at or after ProbeStageClose means the directory did accept and flush real bytes and only teardown failed, while a failure before it means nothing was durably written. Callers legitimately differ here — one warns and keeps running on a teardown failure, another treats every stage as fatal — so the probe reports the stage and never decides.

const (
	// ProbeStageNone is the zero value: every stage passed.
	ProbeStageNone ProbeStage = iota
	// ProbeStageMkdir indicates the directory itself could not be created.
	// Only reachable with WithMkdirMode; without it a missing directory
	// fails at ProbeStageCreate, exactly as a write to a missing parent does.
	ProbeStageMkdir
	// ProbeStageCreate indicates the probe file could not be created: the
	// directory is missing, is not a directory, is read-only, or denies the
	// running UID. It also covers a name that escapes the *os.Root in
	// ProbeWritableInRoot.
	ProbeStageCreate
	// ProbeStageWrite indicates the first data write to the probe file failed
	// (a quota or a full filesystem, which the create alone does not reveal).
	ProbeStageWrite
	// ProbeStageSync indicates flushing the probe file failed, the delayed
	// error a network filesystem reports at fsync rather than at write.
	// Skipped under WithNoSync.
	ProbeStageSync
	// ProbeStageClose indicates closing the probe file failed, the other
	// place a deferred write error surfaces.
	ProbeStageClose
	// ProbeStageRemove indicates the probe file could not be unlinked, so the
	// directory accepts writes but refuses cleanup. ProbeResult.Leaked is then
	// true and the leftover is reclaimable by the package's stale-temp sweep.
	ProbeStageRemove
)

func (ProbeStage) String added in v2.5.0

func (s ProbeStage) String() string

type Result

type Result struct {
	// Path is the cleaned final path the data was written to. It is
	// absolute for the package-level write functions (which require an
	// absolute path); for the *InRoot functions it is root.Name() joined
	// with the cleaned relative name, so it is relative when the *os.Root
	// was opened with a relative path.
	Path string
	// Durable reports whether the write is guaranteed to survive a crash:
	// true only when the file and its parent directory were both fsynced.
	// It is false when WithNoSync was set, or when the parent-directory fsync
	// failed after the rename — in that case the data is present at Path but
	// may not survive an immediate power loss, and the fsync failure is logged
	// at Warn.
	Durable bool
}

Result reports the outcome of an atomic write that reached its final path.

func WriteFile

func WriteFile(ctx context.Context, path string, data []byte, opts ...Option) (Result, error)

WriteFile atomically writes data to path. Mode defaults to 0o644 (override with WithMode). A nil error means the data is at path; check Result.Durable for crash durability.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "data.txt")
	res, _ := atomicfile.WriteFile(context.Background(), path, []byte("hello"))
	data, _ := os.ReadFile(path)
	fmt.Println(string(data), res.Durable)
}
Output:
hello true
Example (WithMkdirMode)
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "nested", "dir", "file.txt")
	_, _ = atomicfile.WriteFile(context.Background(), path, []byte("deep"),
		atomicfile.WithMkdirMode(0o755))
	data, _ := os.ReadFile(path)
	fmt.Println(string(data))
}
Output:
deep
Example (WithMode)
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "secret.txt")
	_, _ = atomicfile.WriteFile(context.Background(), path, []byte("s3cr3t"),
		atomicfile.WithMode(0o600))
	fi, _ := os.Stat(path)
	fmt.Println(fi.Mode().Perm())
}
Output:
-rw-------
Example (WithNoSync)
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "cache.txt")
	res, _ := atomicfile.WriteFile(context.Background(), path, []byte("fast"),
		atomicfile.WithNoSync())
	// WithNoSync trades durability for speed, so the result is not durable.
	fmt.Println(res.Durable)
}
Output:
false

func WriteFileInRoot added in v2.1.0

func WriteFileInRoot(ctx context.Context, root *os.Root, name string, data []byte, opts ...Option) (Result, error)

WriteFileInRoot atomically writes data to name, a path relative to root, with the same temp-then-rename durability and symlink refusal as WriteFile but confined to root: every filesystem operation runs through the *os.Root (Go 1.24+), so a symlink or ".." component in name can never write outside root's tree. It is the write-side analogue of opening a file through an *os.Root and reading it with ReadBoundedFile. Mode defaults to 0o644 (override with WithMode). A nil error means the data is at name; check Result.Durable for crash durability. Result.Path is root's directory joined with the cleaned relative name. A nil root returns ErrUnsafePath.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	root, _ := os.OpenRoot(dir)
	defer func() { _ = root.Close() }()
	// name is relative to the root; a symlink or ".." in it cannot escape the
	// root's tree (Go 1.24+).
	_, _ = atomicfile.WriteFileInRoot(context.Background(), root, "rooted.txt",
		[]byte("confined"))
	// Read it back through the same root with the bounded-read seam.
	f, _ := root.Open("rooted.txt")
	defer func() { _ = f.Close() }()
	data, _ := atomicfile.ReadBoundedFile(context.Background(), f, 1<<20)
	fmt.Println(string(data))
}
Output:
confined

func WriteReader

func WriteReader(ctx context.Context, path string, r io.Reader, opts ...Option) (Result, error)

WriteReader atomically writes the contents of r to path. Mode defaults to 0o644 (override with WithMode). If r implements io.WriterTo it is used for efficient copying; that fast path bypasses the per-Read context check, so cancellation is coarse (per-chunk for chunked sources, post-copy for single-shot sources). ctx is still honored at the durability barrier, so a cancelled write leaves no partial target.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "stream.txt")
	_, _ = atomicfile.WriteReader(context.Background(), path,
		strings.NewReader("streamed"), atomicfile.WithMode(0o600))
	data, _ := os.ReadFile(path)
	fmt.Println(string(data))
}
Output:
streamed
Example (WithMode)
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "stream.txt")
	_, _ = atomicfile.WriteReader(context.Background(), path,
		strings.NewReader("streamed"), atomicfile.WithMode(0o644))
	data, _ := os.ReadFile(path)
	fmt.Println(string(data))
}
Output:
streamed

func WriteReaderInRoot added in v2.1.0

func WriteReaderInRoot(ctx context.Context, root *os.Root, name string, r io.Reader, opts ...Option) (Result, error)

WriteReaderInRoot atomically writes the contents of r to name, a path relative to root, confined to root's tree (see WriteFileInRoot). If r implements io.WriterTo it is used for efficient copying; that fast path bypasses the per-Read context check, so cancellation is coarse (per-chunk for chunked sources, post-copy for single-shot sources). ctx is still honored at the durability barrier, so a cancelled write leaves no partial target. Mode defaults to 0o644 (override with WithMode). A nil root returns ErrUnsafePath.

type SweepResult added in v2.4.0

type SweepResult struct {
	// Removed counts temps reclaimed.
	Removed int
	// Failed counts candidates that could not be inspected or unlinked.
	Failed int
	// Unreadable counts sub-paths the walk could not enter.
	Unreadable int
}

SweepResult is the per-outcome accounting of one CleanupStaleTempsInRoot walk.

Failed and Unreadable are separate because they are different operator problems. Failed means a temp was found and could not be reclaimed (permissions on the file, or an IO error) — orphans are accumulating. Unreadable means a subdirectory could not be entered at all, so it may be hiding orphans nobody has counted. A caller that folds them together cannot tell an operator which one to go fix.

func CleanupStaleTempsInRoot added in v2.4.0

func CleanupStaleTempsInRoot(ctx context.Context, root *os.Root, maxAge time.Duration, opts ...Option) (SweepResult, error)

CleanupStaleTempsInRoot removes temp files orphaned by an interrupted atomic write, confined to root's tree.

It sweeps ONE directory by default, exactly as CleanupStaleTemps does; pass WithRecursive to descend. The two functions differ only in the properties named below, never in how much of the filesystem they touch — that is the caller's explicit choice for both, because the operation deletes files.

Confinement. Every stat and unlink goes through the *os.Root, so a symlink planted under the swept tree cannot redirect a removal outside it, and each candidate is unlinked through a PINNED parent directory (OpenParentInRoot), so an ancestor directory swapped for a symlink cannot redirect it at another file INSIDE the tree either. The ambient variant builds paths with filepath.Join and calls os.Lstat/os.Remove on them, which is safe for a directory the caller owns outright and not safe for one a co-mounting writer can modify underneath — reconstructing an ambient path and handing it to CleanupStaleTemps reintroduces exactly that TOCTOU window.

Memory. The tree is enumerated through WalkDirInRoot, which reads each directory in fixed batches, so a directory holding a large or hostile inventory is not materialized (and sorted) before the sweep looks at its first entry.

Cancellation. The walk stops between entries once ctx is done, so a sweep of a large tree cannot hold up shutdown, and an already-cancelled context does no work. A cancelled sweep returns ctx.Err() alongside the counts accumulated so far.

Unlike CleanupStaleTemps this reports counts instead of logging aggregates: it returns every number a caller needs to narrate the outcome itself, so emitting its own summary would only duplicate that in a second voice. Per-entry diagnostics (which path, which errno) still go to the configured logger at Debug, since those are details the counts cannot carry.

maxAge must be positive; a non-positive value skips the sweep with a warning rather than reaping everything. Only names matching this package's own temp shape are candidates, so a caller-owned file is never removed.

The caller owns root; CleanupStaleTempsInRoot does not close it.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/cplieger/atomicfile/v2"
)

func main() {
	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir)
	// An orphaned temp left by an interrupted write, in a NESTED directory: temps are
	// staged next to their target, so only a recursive sweep finds this one.
	nested := filepath.Join(dir, "example.com")
	_ = os.MkdirAll(nested, 0o750)
	stale := filepath.Join(nested, ".atomicfile-123456.tmp")
	_ = os.WriteFile(stale, []byte("partial"), 0o600)
	old := time.Now().Add(-2 * time.Hour)
	_ = os.Chtimes(stale, old, old)

	root, _ := os.OpenRoot(dir)
	defer root.Close()

	res, _ := atomicfile.CleanupStaleTempsInRoot(context.Background(), root, time.Hour, atomicfile.WithRecursive())
	fmt.Println(res.Removed, res.Failed, res.Unreadable)
}
Output:
1 0 0

type WriteError

type WriteError struct {
	Err   error
	Phase WritePhase
}

WriteError wraps a hard atomic-write failure with the phase that failed. A WriteError always means the data did NOT reach its final path.

func (*WriteError) Error

func (e *WriteError) Error() string

func (*WriteError) Unwrap

func (e *WriteError) Unwrap() error

type WritePhase

type WritePhase int

WritePhase identifies which step of an atomic write failed. Each value appears only on a WriteError, which is returned exclusively for hard failures (the data did not reach its final path). Two outcomes are deliberately absent from this enum because they are not hard failures: a parent-directory fsync failure (surfaced via Result.Durable) and a preserve-ownership chown failure (best-effort, logged at Warn).

const (
	// PhaseTempCreate indicates failure opening the destination for writing:
	// opening the target's parent directory (the absolute-path entry points
	// open it as an *os.Root) or creating the temp file inside it.
	PhaseTempCreate WritePhase = iota + 1
	// PhaseTempWrite indicates failure writing to the temp file.
	PhaseTempWrite
	// PhaseTempChmod indicates failure setting permissions on the temp file.
	PhaseTempChmod
	// PhaseTempSync indicates failure syncing the temp file.
	PhaseTempSync
	// PhaseTempClose indicates failure closing the temp file.
	PhaseTempClose
	// PhaseRename indicates failure renaming temp to the final path.
	PhaseRename
)

func (WritePhase) String

func (p WritePhase) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL