fsutil

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// Execute permission, or search permission for a directory
	AccessExec = 1
	// Write permission
	AccessWrite = 2
	// Read permission
	AccessRead = 4
)

Bits of the mode Access tests, combined with |

Variables

View Source
var ErrSameFile = errors.New("source and destination are the same file")

Error a copy gives when source and destination name the same file

View Source
var ErrSymlinkRoot = errors.New("refusing to remove a tree through a symbolic link")

Error RemoveTree reports for a root that is a symbolic link or a Windows junction, which it never follows

View Source
var SyncDir = syncDir

Flushes a directory entry to disk, skipped on Windows and on any error; durable writes run it after the rename, and tests may replace it to observe them

View Source
var SyncFile = func(f *os.File) error { return f.Sync() }

Flushes a file to disk; every atomic write runs it before the rename, and tests may replace it to simulate a failing disk

Functions

func Access

func Access(path string, mode uint32) bool

Whether the real user may use path with every one of the AccessRead, AccessWrite and AccessExec bits of mode

func Atime

func Atime(fi fs.FileInfo) time.Time

Access time of a file from its stat result to the nanosecond, the modification time when the result carries none

func CleanupTempDir

func CleanupTempDir(dir string, errp *error)

Removes a temporary directory when the function that made it returns, joining a removal failure into *errp; meant for defer

func CopyFile

func CopyFile(src, dst string) error

Copies the content of src to dst, or into dst when that is a directory, then its permission bits with setuid, setgid and sticky, both times and on Linux its extended attributes, symlinks followed; a copy onto itself fails with ErrSameFile, a directory, fifo, socket or device src fails before dst is touched

func CopyLinkMetadata

func CopyLinkMetadata(src, dst string) error

Copies the times, on Linux the extended attributes and on the BSDs and macOS the mode and file flags of the symlink src onto the symlink dst, following neither

func CopyMetadata

func CopyMetadata(src, dst string) error

Copies the permission bits with setuid, setgid and sticky, both times and on Linux the extended attributes of src onto dst, symlinks followed

func CopyRegularFiles

func CopyRegularFiles(src, dst string) (int, error)

Copies the regular files below src into the same places below dst, content only, skipping symlinks and every other kind of entry; gives back how many it copied, zero without error when src is no directory

func CopyTree

func CopyTree(src, dst string, o CopyTreeOptions) error

Copies the directory tree at src to dst, making dst and its parents: each file with its content, permission bits, times and on Linux extended attributes, then each directory's own; a Windows junction is descended into; an entry that fails is skipped and gathered into a *CopyTreeError, while an unreadable src, a dst that exists without DirsExistOK and a Check error stop the copy at once

func CreateTempBeside

func CreateTempBeside(target, prefix, suffix string) (*os.File, error)

Temp file named prefix, random characters and suffix in the directory Replace publishes target into, the directory of the link itself when that one refuses it

func DiskUsage

func DiskUsage(path string) (total, used, free uint64, err error)

Total, used and free bytes of the volume holding path, free counting what an unprivileged user may still use

func Identity

func Identity(path string) (dev, ino uint64, err error)

Device and inode numbers of path, a final symbolic link not followed

func IsRenameContended

func IsRenameContended(err error) bool

Whether a rename failed because another process holds the target, which only happens on Windows

func IsRenameCrossDevice

func IsRenameCrossDevice(err error) bool

Whether a rename failed because the target is on another device or busy, a failure a copy works around

func LockFile

func LockFile(f *os.File) error

Blocks until f holds an exclusive advisory lock on its whole file, a flock retried through interrupted waits

func LookPathIn

func LookPathIn(cmd, path string) (string, error)

Executable cmd names, searched in each directory of path, a list in the form of PATH, by exec.LookPath's rules except that POSIX judges execute permission for the real user: a cmd holding a separator is checked as given, Windows tries the PATHEXT extensions and skips empty entries where POSIX reads them as the working directory, an empty list finds nothing, and a first hit through a relative directory comes back with an error wrapping exec.ErrDot, which on Windows a later absolute directory holding that same file turns into a plain hit

func Move

func Move(src, dst string) (string, error)

Moves the file or tree at src to dst, or into dst when that is a directory, with a rename or, where that fails, a copy keeping links and metadata and then the removal of src; gives back the path moved to, empty when src and dst already name the same directory; an existing destination fails with fs.ErrExist

func PermBits

func PermBits(path string) (uint32, bool)

All twelve permission bits of the file path names, symlinks followed, false when it cannot be read

func ReadText

func ReadText(path string, limit int) (string, error)

First limit characters of the UTF-8 text file at path, all of it for math.MaxInt, a leading byte order mark dropped and \r\n and a lone \r read as \n; bytes that are not UTF-8 within what it reads give a *TextDecodeError

func RemoveOlderThan

func RemoveOlderThan(dir, pattern string, cutoff time.Time) int

Removes the regular files directly in dir whose names match the glob pattern and that were last modified before cutoff, symlinks followed to decide; gives back how many went, skipping whatever cannot be read or removed

func RemoveTempDir

func RemoveTempDir(dir string) error

Removes a temporary directory tree, giving back owner access to every entry or parent that refuses removal and trying it again; entries already gone are no failure

func RemoveTree

func RemoveTree(path string, onError func(op RemoveOp, path string, err error) error) error

Removes the tree at path depth first without following symbolic links or junctions, refusing a linked root with ErrSymlinkRoot; every failure goes to onError with the operation that failed, whose error stops the removal while nil goes on, and a nil onError stops at the first failure

func Replace

func Replace(tmp, target string) (string, error)

Renames tmp over target, or over the file a symlinked target points at so the link stays, copying across devices and retrying a target another Windows process holds; gives back the path written

func RestoreOwner

func RestoreOwner(path string, owner *Owner)

Hands path to owner, ignoring a refusal; a nil owner leaves it alone

func SetPermBits

func SetPermBits(path string, mode uint32) error

Sets all twelve permission bits of path, setuid, setgid and sticky given in their POSIX positions; on Windows only the owner write bit counts, as the read only attribute

func TryLockFile

func TryLockFile(f *os.File) (bool, error)

One attempt at the exclusive lock without waiting, false and no error when another handle holds it

func UnlockFile

func UnlockFile(f *os.File) error

Releases the lock f holds

func WriteFile

func WriteFile(ctx context.Context, path string, data []byte, o WriteOptions) error

Writes data to path through a temp file beside the file path finally names, flushed and renamed over it so readers see the old content or the new and never a mix; the parent directory is made first

Types

type CopyFailure

type CopyFailure struct {
	Src, Dst string
	Err      error
}

One entry a tree copy could not copy and why

func (*CopyFailure) Error

func (f *CopyFailure) Error() string

The entry and the reason, as in copy /a/x to /b/x: open /a/x: permission denied

func (*CopyFailure) Unwrap

func (f *CopyFailure) Unwrap() error

The reason

type CopyTreeError

type CopyTreeError struct{ Failures []CopyFailure }

Every entry a tree copy went on past, in the order it met them

func (*CopyTreeError) Error

func (e *CopyTreeError) Error() string

Each failure, joined by semicolons

func (*CopyTreeError) Unwrap

func (e *CopyTreeError) Unwrap() []error

Each failure as an error of its own, so errors.Is and errors.As look into every one

type CopyTreeOptions

type CopyTreeOptions struct {
	Symlinks    bool
	DirsExistOK bool
	Ignore      IgnoreFunc
	Check       func(dir string, names []string) error
	CopyFile    func(src, dst string) error
}

Settings of CopyTree: Symlinks recreates symbolic links as links rather than copying what they point at; DirsExistOK merges into directories that already exist; Ignore picks the names to skip in each directory; Check vets each directory listing before anything in it is copied, its error stopping the whole copy and coming back unchanged; CopyFile copies each regular file, a copy keeping content and metadata when nil

type FileLock

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

Advisory lock on one lock file, shared by every goroutine and process that takes it, which the goroutine holding it may take again; the holder's pid is stamped in the file after one pad byte while held, so other processes can read it past the byte a Windows lock covers

func SharedFileLock

func SharedFileLock(path string) *FileLock

The FileLock of the lock file at path, the same value for every caller in this process naming the same file

func (*FileLock) Lock

func (l *FileLock) Lock(ctx context.Context, timeout time.Duration) (release func(), err error)

Takes the lock for the calling goroutine, at once when it already holds it, else waiting for other goroutines and processes until it is free, ctx is done or a positive timeout passes; call release once for every successful Lock

type IgnoreFunc

type IgnoreFunc func(dir string, names []string) map[string]bool

Names in one directory listing that a tree copy skips

func IgnorePatterns

func IgnorePatterns(patterns ...string) IgnoreFunc

IgnoreFunc skipping the names that match any of the glob patterns, case folded on Windows

type LockTimeoutError

type LockTimeoutError struct {
	Path      string
	Timeout   time.Duration
	HolderPID int
}

Lock wait that gave up once its timeout passed, with the pid another live process stamped into the lock file, zero when unknown

func (*LockTimeoutError) Error

func (e *LockTimeoutError) Error() string

The lock file, the timeout and the likely holder, as in timed out after 15s waiting for lock file /h/.env.lock; process 4242 probably holds it

func (*LockTimeoutError) Unwrap

func (e *LockTimeoutError) Unwrap() error

Lets errors.Is match os.ErrDeadlineExceeded

type Owner

type Owner struct{ UID, GID int }

Owning user and group ids of a file on a POSIX host

func OwnerOf

func OwnerOf(path string) *Owner

User and group ids owning the file path names, symlinks followed, nil when it cannot be read

type PendingFile

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

Temp file of a streamed atomic write, written through the embedded *os.File and published over its target by Commit; it must not be closed directly

func NewPendingFile

func NewPendingFile(ctx context.Context, path string, o WriteOptions) (*PendingFile, error)

Temp file for an atomic write of path under o, staged where Replace publishes and already carrying the final permission bits; the parent directory is made first, refusing a deleted profile home; publish it with Commit and defer Cleanup

func (*PendingFile) Cleanup

func (p *PendingFile) Cleanup() error

Closes and removes the temp file unless Commit already published it; safe to call any number of times

func (*PendingFile) Commit

func (p *PendingFile) Commit() error

Flushes and closes the temp file and renames it over the target, over the file a symlinked target points at so the link stays, then puts the captured owner and permission bits back and flushes the directory when asked; the temp file is gone whatever the outcome, a panic on the way included

type RemoveOp

type RemoveOp func(path string) error

Operation a tree removal failed at, which an error handler may run again on the same path once it fixed the cause

type TextDecodeError

type TextDecodeError struct {
	Path   string
	Offset int64
}

Bytes of a text file that are not UTF-8, at the offset from the start of the file where decoding failed

func (*TextDecodeError) Error

func (e *TextDecodeError) Error() string

The file and the offset, as in notes.txt: invalid UTF-8 at byte 17

type WriteOptions

type WriteOptions struct {
	Prefix         string
	Mode           *fs.FileMode
	CreateMode     *fs.FileMode
	KeepOwner      bool
	NativeLineEnds bool
	SyncDir        bool
}

Settings of an atomic write: Prefix starts the temp file name (".tmp_" when empty); Mode forces the permission bits, setuid, setgid and sticky included, else the replaced file keeps its bits and a new file gets CreateMode or the umask default; KeepOwner hands the file back to the replaced file's owner; NativeLineEnds makes WriteFile write \n as \r\n on Windows; SyncDir flushes the directory after the rename

Jump to

Keyboard shortcuts

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