Help us shape the future of Go! Take the 2026 Go Developer Survey

compat

package module
v0.5.7 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 23 Imported by: 0

README

compat

Build CodeQL CodeFactor Grade Codecov MegaLinter Go Reference
Release Go Version Last Commit Lines of Code Keep a Changelog License

Portable file identity, extended metadata, and reliable file operations for Go.

compat provides a consistent API for file information that Go's standard os.FileInfo interface does not expose portably, including:

  • access, birth, modification, and metadata-change times;
  • unique file and partition identifiers;
  • hard-link counts;
  • user and group IDs and names;
  • cross-platform file permission setting;
  • atomic file replacement;
  • filesystem and operating-system compatibility helpers.

The package supports Linux, macOS, Windows, BSD systems, Android, iOS, Plan 9, Solaris, illumos, JavaScript/WebAssembly, WASI, TinyGo, and other targets supported by Go.

Contents

Why compat?

The Go standard library intentionally exposes a small, portable file interface. Applications such as backup tools, synchronization engines, file indexes, and duplicate detectors often need additional information that otherwise requires different code for each operating system.

Capability Go standard library compat
Basic name, size, mode, and modification time Yes Yes
Access time Platform-specific Portable API where supported
Birth or creation time Platform-specific Portable API where supported
Metadata-change time Platform-specific Portable API where supported
Hard-link count Platform-specific Portable API where supported
User and group IDs Platform-specific Portable API
User and group names No unified API Portable API
File and partition identity Platform-specific Portable API
Windows SID-to-POSIX ID mapping No Yes
Atomic file replacement No unified API Yes, where supported
Filesystem capability checks Limited Yes

compat does not replace the standard library for ordinary file access. Use os, io, io/fs, and path/filepath when their APIs already provide everything your application needs.

Use cases

compat is intended for software that must interpret file metadata consistently across operating systems, including:

  • backup and restore tools;
  • file synchronization software;
  • duplicate-file detectors;
  • file indexes and search tools;
  • installers and self-updaters;
  • archival and migration utilities;
  • cross-platform development tools;
  • applications that need stable file identity on Windows and Unix-like systems.

Installation

go get github.com/rasa/compat

Documentation for the public API is available on pkg.go.dev.

Quick start

Read portable file metadata
package main

import (
	"fmt"
	"log"

	"github.com/rasa/compat"
)

func main() {
	info, err := compat.Stat("example.txt")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Name:       %s\n", info.Name())
	fmt.Printf("Size:       %d bytes\n", info.Size())
	fmt.Printf("Mode:       0o%o (%v)\n", info.Mode(), info.Mode())
	fmt.Printf("Modified:   %s\n", info.ModTime())
	fmt.Printf("Accessed:   %s\n", info.ATime())

	if compat.SupportsBTime() {
		fmt.Printf("Created:    %s\n", info.BTime())
	}

	if compat.SupportsCTime() {
		fmt.Printf("Changed:    %s\n", info.CTime())
	}

	fmt.Printf("Owner:      %s (%d)\n", info.User(), info.UID())
	fmt.Printf("Group:      %s (%d)\n", info.Group(), info.GID())
	fmt.Printf("Links:      %d\n", info.Links())
	fmt.Printf("File ID:    %d:%d\n", info.PartitionID(), info.FileID())

	// Some extended values may require an additional system call.
	if err := info.Error(); err != nil {
		log.Printf("some extended metadata could not be read: %v", err)
	}
}

Stat follows symbolic links. Use Lstat when the returned metadata should describe the symbolic link itself.

Write a file atomically
package main

import (
	"log"

	"github.com/rasa/compat"
)

func main() {
	data := []byte("configuration data\n")

	err := compat.WriteFile(
		"config.txt",
		data,
		0o600,
		compat.WithAtomicity(true), // optional
	)
	if err != nil {
		log.Fatal(err)
	}
}

With WithAtomicity(true), the destination is either fully replaced or left unchanged when the operating system and filesystem support atomic replacement.

On Plan 9, creating a new file atomically is supported, but atomically replacing an existing file is not. WriteFile returns an error matching errors.ErrUnsupported in that case. Applications that explicitly accept a non-atomic fallback can also pass:

compat.WithNonAtomicReplace(true)

Atomic replacement and durable persistence are different guarantees. An atomic rename prevents readers from observing a partially written destination; it does not necessarily guarantee that the data has reached permanent storage after a power loss.

Compare file identity

Use the file and partition identifiers returned by Stat to determine whether two paths refer to the same underlying file:

package main

import (
	"fmt"
	"log"

	"github.com/rasa/compat"
)

func main() {
	first, err := compat.Stat("first.txt")
	if err != nil {
		log.Fatal(err)
	}
	second, err := compat.Stat("second.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("same file:      %v\n", compat.SameFile(first, second))
	fmt.Printf("same partition: %v\n", compat.SamePartition(first, second))

	// or alternatively:
	same1, err := compat.SameFiles("first.txt", "second.txt")
	if err != nil {
		log.Fatal(err)
	}
	same2, err := compat.SamePartitions("first.txt", "second.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("same file:      %v\n", same1)
	fmt.Printf("same partition: %v\n", same2)
}

Core API

Metadata and identity
Function or type Purpose
Stat Returns extended information for a path and follows symbolic links
Lstat Returns extended information about a path without following its final symbolic link
Fstat Returns extended information for an open file where supported
FileInfo Extends os.FileInfo with portable metadata and identity methods
SameFile Reports whether two compat.FileInfo values describe the same file
SamePartition Reports whether two files reside on the same partition
PartitionType Reports the underlying filesystem or partition type
SupportsATime Reports operating-system support for access time
SupportsATimeSetting Reports support for setting access time
SupportsBTime Reports operating-system support for birth time
SupportsCTime Reports operating-system support for metadata-change time
SupportsFstat Reports support for Fstat
SupportsLinks Reports support for hard-link counts
SupportsSymlinks Reports operating-system support for symbolic links
SupportsUmask Reports support for Umask
UserIDSource Describes how user IDs are represented on the current platform
File operations

The package includes cross-platform variants of common file operations, including:

  • Chmod and Fchmod
  • Create, CreateTemp
  • Link and Symlink
  • Mkdir, Mkdirall and MkdirTemp
  • Nice and Renice
  • Open, and OpenFile
  • ReadDir and WalkDir
  • Rename
  • Remove, and RemoveAll
  • Stat, Fstat and LStat
  • Umask
  • WriteFile and WriteReader

Several operations accept functional options:

Option Purpose Used by
WithAtomicity Requests atomic file creation or replacement (other than Plan 9) WriteFile, WriteReader
WithFileMode Sets the requested file mode Create, CreateTemp, MkdirTemp, Open, OpenFile, WriteFile, WriteReader
WithDefaultFileMode Changes the default mode used when no explicit mode is supplied Create, CreateTemp, Open, OpenFile, WriteFile, WriteReader
WithDeleteOnClose Deletes file when closed Create, CreateTemp, Open, OpenFile
WithKeepFileMode Preserves the mode of an existing destination WriteFile, WriteReader
WithOpenFlags Adds file-open flags Create, CreateTemp, Open, OpenFile
System specific
WithNonAtomicReplace Allows a non-atomic replacement where atomic replacement is unavailable (Plan 9 only) WriteFile, WriteReader
WithRetryTimeout Retries selected operations for a bounded period (Windows/macOS only) Rename, Remove, RemoveAll
WithReadOnlyMode Controls Windows read-only attribute handling (Windows only) Chmod, Create, CreateTemp, Fchmod, Open, OpenFile, WriteFile, WriteReader
WithSetSymlinkOwner Requests ownership adjustment for symbolic links (Windows only) Symlink
WithSkipACLs Skips setting ACLs (Windows only) Chmod, Fchmod

An option may apply only to the operations documented for it. Options that control OS-specific behavior are ignored on other operating systems.

Behavior and limitations

Cross-platform filesystem behavior cannot be made identical in every case. Callers should account for the following:

  • Filesystem support varies. An operating system may support a metadata field even when a particular local, network, virtual, or removable filesystem does not.
  • Capability functions describe platform support. A Supports* result does not override filesystem-specific limitations, mount options, permissions, or runtime restrictions.
  • Unavailable values use documented zero or sentinel values. Check FileInfo.Error() after reading extended values that may require additional system calls.
  • Windows permissions are represented through ACLs. POSIX mode bits are mapped to Windows access-control entries and cannot express every Windows ACL configuration.
  • User and group identity differ by operating system. Windows SIDs are mapped to integer values compatible with Cygwin, MSYS2, and Git for Windows. Plan 9 uses hashes of user and group names.
  • Atomic replacement is not durability. A successful atomic rename does not by itself guarantee persistence after a system or storage failure.
  • Symbolic-link support may require privileges or configuration. This is especially relevant on Windows and restricted mobile environments.
  • Network and virtual filesystems may have different semantics. Test the actual filesystems your application supports.

The project is currently pre-v1. Review CHANGELOG.md for breaking changes before upgrading between releases.

Platform support

Extended file metadata

Stat, Fstat, and Lstat return a FileInfo value. Support for extended metadata depends on both the operating system and the underlying filesystem.

OS PartitionID()/
FileID()*
Links()* ATime()*
(last
Accessed)
BTime()*
(Birthed/
created)
CTime()*
(metadata
last Changed)
UID()/GID()
AIX ✅ ✅ ✅ ❌ ✅ ✅
Android ✅ ✅§ ✅ ❌ ✅ ✅
Dragonfly ✅ ✅ ✅ ✖️ ✅ ✅
FreeBSD ✅ ✅ ✅ ✅ ✅ ✅
Illumos ✅ ✅ ✅ ✖️ ✅ ✅
iOS ✅ ✅ ✅ ✅ ✅ ✅
Js/
WASM
✅ ✅ ✅ ❌ ✅ ✅
Linux ✅ ✅ ✅ ✅ ✅ ✅
macOS ✅ ✅ ✅ ✅ ✅ ✅
NetBSD ✅ ✅ ✅ ✅ ✅ ✅
OpenBSD ✅ ✅ ✅ ✖️ ✅ ✅
Plan9 ✅ ❌ ✅ ❌ ❌ ☑️‖
Solaris ✅ ✅ ✅ ✖️ ✅ ✅
Wasip1/
WASM
✅ ✅ ✅† ❌ ✅ ✅
Windows ✅ ✅ ✅ ✅ ✅ ✅‡

Key

  • ✅ Fully supported by the operating-system implementation.
  • ☑️ Partially supported. See footnote.
  • ✖️ Not currently implemented although the operating system may support it.
  • ❌ Not implemented because the operating system appears not to provide it.

* Actual support depends on the underlying filesystem. See Comparison of file systems for details.
† Not supported when compiled with TinyGo.
‡ Windows values use the same SID-to-integer mapping as Cygwin, MSYS2, and Git for Windows.
§ Android 7/API 24 and later appear to disallow hard-link creation by default.
‖ The UID() and GID() values are 32-bit hashes of the user and group names.

Other operations
OS Chmod()* Fstat() Nice()/
Renice()
PartitionType() Symlink() Umask()
AIX ✅ ☑️‖ ✅ ✅* ✅ ✅
Android ✅ ✅ ✅ ✅ ✅ ✅
Dragonfly ✅ ☑️‖ ✅ ✅ ✅ ✅
FreeBSD ✅ ✅ ✅ ✅‡ ✅ ✅
Illumos ✅ ☑️‖ ✅ ✅ ✅ ✅
iOS ✅ ✅ ☑️¶ ✅ ✅ ✅
Js/
WASM
❌ ☑️‖ ☑️¶ ✅ ❌ ✅
Linux ✅ ✅ ✅ ✅ ✅ ✅
macOS ✅ ✅ ✅ ✅ ✅ ✅
NetBSD ✅ ☑️‖ ✅ ✅‡ ✅ ✅
OpenBSD ✅ ☑️‖ ✅ ✅‡ ✅ ✅
Plan9 ✅ ☑️‖ ✅ ✅ ❌ ❌
Solaris ✅ ☑️‖ ✅ ✅ ✅ ✅
Wasip1/
WASM
❌ ☑️‖ ☑️¶ ✅ ❌ ✅†
Windows ✅ ✅ ✅ ✅ ✅ ✅§

Key

  • ✅ Fully supported.
  • ☑️ Partially supported. See footnote.
  • ✖️ Not currently implemented although the operating system may support it.
  • ❌ Not implemented because the operating system appears not to provide it.

* Actual support depends on the underlying filesystem. See Comparison of file systems for details.
† Not supported when compiled with TinyGo.
‡ Not supported on openbsd/ppc64, netbsd/386, freebsd/riscv64, or aix/ppc64 with CGO because of compilation limitations.
§ Implemented through the UMASK=0NNN environment variable.
‖ Will fail on relative filenames where the current directory is changed after opening the file.
Nice always returns 0, and Renice performs no operation.

Environment variables

Runtime configuration
UMASK — Windows only

Sets the initial default umask. When unset, 0o022 is used.

Test configuration

The following variables are used only by the project's test suite.

COMPAT_DEBUG
  • Set to DEBUG to emit additional debugging information.
  • Set to DUMP to dump Windows ACL information.
COMPAT_DEBUG_FS

Selects a filesystem to test. Set it to All to test every available filesystem.

Supported test filesystems include:

Linux

  • Btrfs
  • exFAT
  • ext2
  • ext3
  • ext4
  • F2FS
  • FAT
  • FAT32
  • NTFS
  • ReiserFS
  • XFS

macOS

  • APFS
  • exFAT
  • FAT32
  • HFS+
  • HFS+J
  • HFSX
  • JHFS+
  • JHFS+X
  • UDF

Windows

  • exFAT
  • FAT32
  • FAT — currently disabled
  • NTFS
  • ReFS
COMPAT_DEBUG_FS_PATH

Sets the path used to mount test filesystems.

Defaults:

OS Path
Linux /mnt/
macOS /Volumes/
Windows Z:\
COMPAT_DEBUG_FS_SIZE

Sets the size of the virtual test volume. The default is 2GB.

COMPAT_DEBUG_PERM — Windows only

Sets a specific file-permission value to test. When unset, the suite tests all 511 nonzero combinations of the user, group, and other permission bits.

Comparing Stat Across Linux and Windows

package main

import (
	"log"
	"os"

	"github.com/rasa/compat"
)

func main() {
	hello := []byte("Hello World!")
	err := compat.WriteFile("hello.txt", hello, 0o654)
	if err != nil {
		log.Fatal(err)
	}

	fi, err := compat.Stat("hello.txt")
	if err != nil {
		log.Fatal(err)
	}

	print(fi.String())
}

On Linux, the above program prints:

Name:   hello.txt
Size:   12
Mode:   0o654 (-rw-r-xr--)
ModTime:2025-08-14 09:25:27.190602462 -0700 PDT // last Modified
ATime:  2025-08-14 09:25:27.190602462 -0700 PDT // last Accessed
BTime:  2025-08-14 09:25:27.190602462 -0700 PDT // Birthed/created
CTime:  2025-08-14 09:25:27.190602462 -0700 PDT // metadata last Changed
IsDir:  false
Links:  1                                       // number of hard links
UID:    1000 (ross)                             // user ID
GID:    1000 (ross)                             // group ID
PartID: 64512                                   // unique partition (device) ID
FileID: 18756713                                // unique file ID on the partition

On Windows, the program prints:

Name:   hello.txt
Size:   12
Mode:   0o654 (-rw-r-xr--)
ModTime:2025-08-14 09:28:50.4214934 -0700 PDT
ATime:  2025-08-14 09:28:50.4214934 -0700 PDT
BTime:  2025-08-14 09:28:50.4209614 -0700 PDT
CTime:  2025-08-14 09:28:50.4214934 -0700 PDT
IsDir:  false
Links:  1
UID:    197609 (domain\ross)
GID:    197121 (domain\None)
PartID: 8
FileID: 844424931319952

icacls shows:

icacls hello.txt

hello.txt domain\ross:(R,W,D)
          domain\None:(RX)
          Everyone:(R)

Powershell shows:

powershell -command "Get-Acl hello.txt | Format-List"

Path   : Microsoft.PowerShell.Core\FileSystem::C:\path\to\hello.txt
Owner  : domain\ross
Group  : domain\None
Access : Everyone Allow  Read, Synchronize
         domain\None Allow  ReadAndExecute, Synchronize
         domain\ross Allow  Write, Delete, Read, Synchronize
Audit  :
Sddl   : O:S-1-5-21-2970224322-3395479738-1485484954-1001G:S-1-5-21-2970224322-3395479738-1485484954-513D:P(A;;FR;;;WD)(A;;0x1200a9;;;S-1-5-21-2970224322-3395479738-1485484954-5
         19f;;;S-1-5-21-2970224322-3395479738-1485484954-1001)

Cygwin's stat shows:

$ stat hello.txt
  File: hello.txt
  Size: 12              Blocks: 1          IO Block: 65536  regular file
Device: 0,8     Inode: 844424931319952  Links: 1
Access: (0754/-rwxr-xr--)  Uid: (197609/    ross)   Gid: (197121/    None)
Access: 2025-08-14 09:28:50.421493400 -0700
Modify: 2025-08-14 09:28:50.421493400 -0700
Change: 2025-08-14 09:28:50.421493400 -0700
 Birth: 2025-08-14 09:28:50.420961400 -0700

Git for Windows's stat shows:

$ stat hello.txt
  File: hello.txt
  Size: 11              Blocks: 1          IO Block: 65536  regular file
Device: 8h/8d   Inode: 844424931319952  Links: 1
Access: (0644/-rw-r--r--)  Uid: (197609/    ross)   Gid: (197121/ UNKNOWN)
Access: 2025-08-14 09:30:06.729683700 -0700
Modify: 2025-08-14 09:28:50.421493400 -0700
Change: 2025-08-14 09:28:50.421493400 -0700
 Birth: 2025-08-14 09:28:50.420961400 -0700

Go applications commonly rely on focused packages that normalize one category of operating-system behavior. The following projects solve problems adjacent to, but generally separate from, portable file metadata.

Package Capability Purpose
99designs/keyring Credential storage Provides a common interface for macOS Keychain, Windows Credential Manager, Secret Service, KWallet, pass, KeyCtl, and other credential stores
adrg/xdg Application directories Provides standard configuration, data, cache, state, runtime, and user-directory paths across Unix, Windows, macOS, and Plan 9
distatus/battery Battery and AC status Reports battery capacity, charging state, and power information across supported operating systems
ebitengine/purego Native-library interoperability Calls functions in native shared libraries without requiring conventional Cgo wrappers
fsnotify/fsnotify Filesystem change notifications Wraps facilities such as inotify, kqueue, ReadDirectoryChangesW, and FEN behind one event API
gofrs/flock File locking Provides a portable file-locking interface over platform-specific locking mechanisms
hymkor/trash-go Move files to trash Uses the Windows Recycle Bin and experimentally supports Freedesktop-style trash directories on non-Windows systems
mattn/go-colorable Portable colored output Supports ANSI-colored output through Windows console handling and ordinary writers on other systems
mattn/go-isatty Terminal detection Determines whether a file descriptor refers to a terminal or character device
pkg/browser Open URLs and files Opens URLs, files, or reader contents through the platform's browser facilities
shirou/gopsutil System and process information Provides cross-platform CPU, memory, host, disk, network, and process information
tklauser/numcpus Available CPU count Determines the number of CPUs available to the current process using platform-specific facilities

Contributing

Issues and pull requests are welcome.

Filesystem behavior is highly platform-specific. Bug reports are most useful when they include:

  • the Go version;
  • GOOS and GOARCH;
  • the operating-system version;
  • the filesystem or volume type;
  • whether CGO or TinyGo was used;
  • a minimal reproducer;
  • the expected and actual results.

Before submitting a pull request, run the applicable tests and format the code with the standard Go tools.

License

compat is available under the MIT License.

Documentation

Overview

Package compat is a pure-Go library providing unified access to file and device metadata, atomic file operations, process priority, etc. on all major operating systems, include Windows, Linux, macOS, Android, iOS, and many others.

Index

Constants

View Source
const (
	// CreatePerm is the FileMode used by os.Create() (and compat.Create()).
	CreatePerm os.FileMode = 0o666
	// CreateTempPerm is the FileMode used by os.CreateTemp() (and
	// compat.CreateTemp()).
	CreateTempPerm os.FileMode = 0o600
	// MkdirTempPerm is the FileMode used by os.MkdirTemp() (and
	// compat.MkdirTemp()).
	MkdirTempPerm os.FileMode = 0o700

	// DefaultAppleDirPerm is the FileMode returned for directories by
	// golang's os.Stat() function on Apple based systems
	// when the directory is on a filesystem that doesn't support
	// macOS/iOS permissions, such as exFAT, or FAT32.
	DefaultAppleDirPerm os.FileMode = 0o700
	// DefaultAppleFilePerm is the FileMode returned for files by
	// golang's os.Stat() function on Apple based systems
	// when the file is on a filesystem that doesn't support
	// macOS/iOS permissions, such as exFAT, or FAT32.
	DefaultAppleFilePerm os.FileMode = 0o700

	// DefaultUnixDirPerm is the FileMode returned for directories by
	// golang's os.Stat() function on non-Apple/non-Windows based systems
	// when the directory is on a filesystem that doesn't support
	// Unix permissions, such as exFAT, or FAT32.
	DefaultUnixDirPerm os.FileMode = 0o777
	// DefaultUnixFilePerm is the FileMode returned for files by
	// golang's os.Stat() function on non-Apple/non-Windows based systems
	// when the file is on a filesystem that doesn't support
	// Unix permissions, such as exFAT, or FAT32.
	DefaultUnixFilePerm os.FileMode = 0o777

	// DefaultWindowsDirPerm is the FileMode returned for directories by
	// golang's os.Stat() function on Windows based systems
	// when the directory is on a filesystem that doesn't support Windows'
	// Access Control Lists (ACLS), such as exFAT, or FAT32.
	DefaultWindowsDirPerm os.FileMode = 0o777
	// DefaultWindowsFilePerm is the FileMode returned for files by
	// golang's os.Stat() function on Windows based systems
	// when the file is on a filesystem that doesn't support Windows'
	// Access Control Lists (ACLS), such as exFAT, or FAT32.
	DefaultWindowsFilePerm os.FileMode = 0o666
)
View Source
const (
	// ReadOnlyModeSet set a file's read-only attribute, if the specified
	// perm FileMode has the user writable bit (0o200) set. Otherwise, it will
	// resets (clears) it. (Windows only).
	//
	// Deprecated: Ues ReadOnlyModeFromPermissions instead.
	//
	// This constant will be removed in a future release.
	ReadOnlyModeSet = ReadOnlyModeFromPermissions
	// ReadOnlyModeReset does not set a file's read-only attribute, and if it's
	// set, it resets (clears) it. (Windows only).
	//
	// Deprecated: Use ReadOnlyModeClear instead.
	//
	// This constant will be removed in a future release.
	ReadOnlyModeReset = ReadOnlyModeClear

	// UserIDSourceIsInt defines if the OS uses an int to identify the user.
	//
	// Deprecated: Use UserIDSourceIsInteger instead.
	//
	// This constant will be removed in a future release.
	UserIDSourceIsInt = UserIDSourceIsInteger
)
View Source
const (
	// MaxNice is the maximum value returned by Nice().
	MaxNice = 19
	// MinNice is the minimum value returned by Nice().
	MinNice = -20
)
View Source
const (
	IsAIX       = runtime.GOOS == "aix"
	IsAndroid   = runtime.GOOS == "android"
	IsDarwin    = runtime.GOOS == "darwin"
	IsDragonfly = runtime.GOOS == "dragonfly"
	IsFreeBSD   = runtime.GOOS == "freebsd"
	IsIllumos   = runtime.GOOS == "illumos"
	IsIOS       = runtime.GOOS == "ios"
	IsJS        = runtime.GOOS == "js"
	IsLinux     = runtime.GOOS == "linux"
	IsNetBSD    = runtime.GOOS == "netbsd"
	IsOpenBSD   = runtime.GOOS == "openbsd"
	IsPlan9     = runtime.GOOS == "plan9"
	IsSolaris   = runtime.GOOS == "solaris"
	IsWasip1    = runtime.GOOS == "wasip1"
	IsWindows   = runtime.GOOS == "windows"
)
View Source
const (
	IsApple   = IsDarwin || IsIOS
	IsBSD     = IsDragonfly || IsFreeBSD || IsNetBSD || IsOpenBSD
	IsBSDLike = IsApple || IsBSD
	IsSolaria = IsIllumos || IsSolaris
)
View Source
const (
	Is386      = runtime.GOARCH == "386"
	IsAmd64    = runtime.GOARCH == "amd64"
	IsArm      = runtime.GOARCH == "arm"
	IsArm64    = runtime.GOARCH == "arm64"
	IsLoong64  = runtime.GOARCH == "loong64"
	IsMips     = runtime.GOARCH == "mips"
	IsMips64   = runtime.GOARCH == "mips64"
	IsMips64le = runtime.GOARCH == "mips64le"
	IsMipsle   = runtime.GOARCH == "mipsle"
	IsPpc64    = runtime.GOARCH == "ppc64"
	IsPpc64le  = runtime.GOARCH == "ppc64le"
	IsRiscv64  = runtime.GOARCH == "riscv64"
	IsS390x    = runtime.GOARCH == "s390x"
	IsWasm     = runtime.GOARCH == "wasm"
)
View Source
const (
	IsX86CPU  = Is386 || IsAmd64
	IsArmCPU  = IsArm || IsArm64
	IsMipsCPU = IsMips || IsMips64 || IsMips64le || IsMipsle
	IsPpcCPU  = IsPpc64 || IsPpc64le
)
View Source
const IsTinygo = false // was runtime.Compiler == "tinygo"

IsTinygo is true if the go compiler is tinygo.

View Source
const IsUnix = true

IsUnix is true if the unix build tag has been set. Currently, it's equivalent to: IsAIX || IsAndroid || IsApple || IsBSD || IsLinux || IsSolaria.

View Source
const UnknownID = int(-1)

UnknownID is returned when the UID or GID could not be determined.

Variables

View Source
var ErrInvalidNice = errors.New("invalid nice value")
View Source
var ErrMountpointNotFound = errors.New("mountpoint not found")
View Source
var IsAct = os.Getenv("ACT") == "true"

IsAct is true when running github actions locally using the act command.

View Source
var SkipAll = fs.SkipAll

SkipAll is used as a return value from WalkDirFunc to indicate that all remaining files and directories are to be skipped. It is not returned as an error by any function.

View Source
var SkipDir = fs.SkipDir

SkipDir is used as a return value from WalkDirFunc to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.

View Source
var UnderlyingGoVersion = GoVersion

Deprecated: Use GoVersion() instead.

This function will be removed in a future release.

Functions

func BuildBits added in v0.4.1

func BuildBits() int

BuildBits returns the number of CPU bits for the build target. For 386, arm, mips, and mipsle, it's 32. For all other targets, it's 64.

func CPUBits added in v0.4.1

func CPUBits() (int, error)

CPUBits returns the number of bits on the CPU. Currently, on plan9, and wasm, BuildBits() is returned.

func Chmod added in v0.4.1

func Chmod(name string, mode os.FileMode, fns ...Option) error

Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type [*PathError].

A different subset of the mode bits are used, depending on the operating system.

On Unix, the mode's permission bits, [ModeSetuid], [ModeSetgid], and [ModeSticky] are used.

On Windows, the mode's permission bits are used to set the appropriate ACL entries.

In addition, the 0o200 bit (owner writable) is used to control whether the file's read-only attribute is set or cleared. For compatibility with Go 1.12 and earlier, use a non-zero mode.

On Plan 9, the mode's permission bits, [ModeAppend], [ModeExclusive], and [ModeTemporary] are used.

func Create added in v0.4.1

func Create(name string, fns ...Option) (*os.File, error)

Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0o666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode [O_RDWR]. The directory containing the file must already exist. If there is an error, it will be of type [*PathError].

func CreateTemp added in v0.4.1

func CreateTemp(dir, pattern string, fns ...Option) (*os.File, error)

CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". The file is created with mode 0o600 (before umask). If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by [TempDir]. Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file. The caller can use the file's Name method to find the pathname of the file. It is the caller's responsibility to remove the file when it is no longer needed.

func Fchmod added in v0.5.4

func Fchmod(fp *os.File, mode os.FileMode, fns ...Option) error

Fchmod changes the mode of the file to mode. If there is an error, it will be of type [*PathError].

func FormatDirEntry added in v0.5.2

func FormatDirEntry(dir DirEntry) string

FormatDirEntry returns a formatted version of dir for human readability. Implementations of DirEntry can call this from a String method. The outputs for a directory named subdir and a file named hello.go are:

d subdir/
- hello.go

func FormatFileInfo added in v0.5.4

func FormatFileInfo(info FileInfo) string

FormatFileInfo returns a formatted version of info for human readability. Implementations of FileInfo can call this from a String method. The output for a file named "hello.go", 100 bytes, mode 0o644, created January 1, 1970 at noon is

-rw-r--r-- 100 1970-01-01 12:00:00 hello.go

func GetUmask added in v0.4.1

func GetUmask() int

GetUmask returns the current umask value. On Plan9 and Wasip1, the function always returns zero.

func Getegid added in v0.5.3

func Getegid() (int, error)

Getegid returns the effective default Group ID for the current user. On Windows, the user's primary group's SID is converted to its POSIX equivalent, which is compatible with Cygwin, Git for Windows, MSYS2, etc. On Plan9, Getegid returns a 32-bit hash of the user's group's name, as provided by golang's os/user package.

func Geteuid added in v0.5.3

func Geteuid() (int, error)

Geteuid returns the effective User ID for the current user. On Windows, the user's SID is converted to its POSIX equivalent, which is compatible with Cygwin, Git for Windows, MSYS2, etc. On Plan9, Geteuid returns a 32-bit hash of the user's name.

func Getgid added in v0.5.0

func Getgid() (int, error)

Getgid returns the default Group ID for the current user. On Windows, the user's primary group's SID is converted to its POSIX equivalent, which is compatible with Cygwin, Git for Windows, MSYS2, etc. On Plan9, Getgid returns a 32-bit hash of the user's group's name, as provided by golang's os/user package.

func Getuid added in v0.5.0

func Getuid() (int, error)

Getuid returns the User ID for the current user. On Windows, the user's SID is converted to its POSIX equivalent, which is compatible with Cygwin, Git for Windows, MSYS2, etc. On Plan9, Getuid returns a 32-bit hash of the user's name.

func GoVersion added in v0.5.5

func GoVersion() string

GoVersion returns the effective Go toolchain version string ("goX.Y") for the current environment. - On standard Go: returns runtime.Version() (already "go1.xx"). - On TinyGo: picks the highest Go version supported based on thresholds.

func IsRoot added in v0.4.2

func IsRoot() (bool, error)

IsRoot returns true if the user is (effectively) root on a non-Windows system, or is running with elevated privileges (administrator rights) on a Windows system.

func IsUnsupportedError deprecated added in v0.5.6

func IsUnsupportedError(err error) bool

IsUnsupportedError returns true if err indicates the function is unsupported.

Deprecated: Do not use.

This function will be removed in a future release.

func IsWSL added in v0.3.0

func IsWSL() bool

IsWSL returns true if running inside a Windows Subsystem for Linux (WSL) environment, otherwise false.

It's counter-intuitive that IsWSL() returns false in Windows, but here's why: WSL can run executables built to run on Linux, and those built to run on Windows. For example, executing `whoami` will run WSL's `/usr/bin/whoami`, but append a `.exe`, and execute `whoami.exe`, then WSL will instead run Windows' whoami, in `C:/Windows/System32/whoami.exe`. But it doesn't appear to me that executables built to run on Windows can't tell they were started from inside a WSL environment. For example, the program doesn't see the `WSL_DISTRO_NAME“ environment variable that other programs run inside WSL see. Hence, this function must return false.

func Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file. If there is an error, it will be of type *LinkError.

func Mkdir added in v0.4.1

func Mkdir(name string, perm os.FileMode) error

Mkdir creates a new directory with the specified name and perm's permission bits (before umask). If there is an error, it will be of type [*PathError].

func MkdirAll added in v0.4.1

func MkdirAll(path string, perm os.FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The perm's permission bits (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

func MkdirTemp added in v0.4.1

func MkdirTemp(dir, pattern string, fns ...Option) (string, error)

MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. The directory is created with mode 0o700 (before umask). If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when it is no longer needed.

func Nice added in v0.2.0

func Nice() (int, error)

Nice gets the CPU process priority. The return value is in a range from -20 (least nice), to 19 (most nice), even on non-Unix systems such as Windows, plan9, etc. If not supported by the operating system, 0 is returned.

func OpenFile added in v0.4.1

func OpenFile(name string, flag int, perm os.FileMode, fns ...Option) (*os.File, error)

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag ([O_RDONLY] etc.). If the file does not exist, and the [O_CREATE] flag is passed, it is created with perm's permission bits (before umask); the containing directory must exist. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type [*PathError].

func PartitionType added in v0.5.0

func PartitionType(ctx context.Context, path string) (string, error)

PartitionType returns the filesystem type (e.g., "apfs", "btrfs", "exfat", "ext4", "f2fs", "fat32", "hfs+", "ntfs", "refs", "udf", "xfs", etc.) for the disk partition that contains path. The value returned is always lower case.

func Remove added in v0.5.2

func Remove(name string, fns ...Option) error

Remove removes the named file or directory. If there is an error, it will be of type [*PathError].

func RemoveAll added in v0.5.2

func RemoveAll(path string, fns ...Option) error

RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type [*PathError].

func Rename added in v0.4.2

func Rename(source, destination string, fns ...Option) error

Rename atomically replaces the destination file or directory with the source. It is guaranteed to either replace the target file entirely, or not change either file.

On Plan 9, atomic replacement of an existing file is not supported. If the destination exists, WriteReader returns an error matching errors.ErrUnsupported and leaves the destination unchanged. To work around this issue, use the WithNonAtomicReplace option.

func Renice added in v0.2.0

func Renice(nice int) error

Renice sets the CPU process priority. The nice parameter can range from -20 (least nice), to 19 (most nice), even on non-Unix systems such as Windows, plan9, etc. If not supported by the operating system, nil is returned.

func SameFile

func SameFile(fi1, fi2 FileInfo) bool

SameFile reports whether fi1 and fi2 describe the same file. For example, on Unix this means that the partition (device) and inode fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SamePartition only applies to results returned by this package's Stat. It returns false in other cases.

func SameFiles

func SameFiles(name1, name2 string) (bool, error)

SameFiles reports whether name1 and name2 are the same file. The function follow symlinks.

func SamePartition added in v0.4.0

func SamePartition(fi1, fi2 FileInfo) bool

SamePartition reports whether fi1 and fi2 describe files on the same disk partition. For example, on Unix this means that the partition (device) fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SamePartition only applies to results returned by this package's Stat. It returns false in other cases.

func SamePartitions added in v0.4.0

func SamePartitions(name1, name2 string) (bool, error)

SamePartitions reports whether name1 and name2 are files on the same disk partition. The function follow symlinks.

func SetOptions added in v0.5.6

func SetOptions(fns ...Option)

func SupportsATime

func SupportsATime() bool

SupportsATime returns true if FileInfo's ATime() function is supported by the OS.

func SupportsATimeSetting added in v0.5.6

func SupportsATimeSetting() bool

SupportsATimeSetting returns true setting a files's atime is supported by the OS.

func SupportsAtomicReplace added in v0.5.6

func SupportsAtomicReplace() bool

SupportsAtomicReplace returns true if atomically replacing a file is supported by the OS.

func SupportsBTime

func SupportsBTime() bool

SupportsBTime returns true if FileInfo's BTime() function is supported by the OS.

func SupportsCTime

func SupportsCTime() bool

SupportsCTime returns true if FileInfo's CTime() function is supported by the OS.

func SupportsFstat added in v0.5.4

func SupportsFstat() bool

SupportsFstat returns true if the Fstat() function is supported by the OS.

func SupportsLinks() bool

SupportsLinks returns true if FileInfo's Links() function is supported by the OS.

func SupportsNice added in v0.5.4

func SupportsNice() bool

SupportsNice returns true if the Nice() function is supported by the OS.

func SupportsRelativeFstat added in v0.5.6

func SupportsRelativeFstat() bool

SupportsRelativeFstat always returns true. Deprecated. Will be removed in a future version.

func SupportsSymlinks() bool

SupportsSymlinks returns true if the os.Symlinks() function is supported by the OS. Note that the underlying filesystem may not allow symlinks.

func SupportsUmask added in v0.5.6

func SupportsUmask() bool

SupportsUmask returns true if the Umask() function is supported by the OS.

func Symlink(oldname, newname string, fns ...Option) error

Symlink creates newname as a symbolic link to oldname. On Windows, a symlink to a non-existent oldname creates a file symlink; if oldname is later created as a directory the symlink will not work. If there is an error, it will be of type *LinkError.

func Umask added in v0.4.1

func Umask(newMask int) int

Umask sets the umask to umask, and returns the previous value. On Windows, the initial umask value is 022 octal, and can be changed by setting environmental variable UMASK, to an octal value. For example: `set UMASK=002`. Leading zeros and 'o's are allowed, and ignored. On Plan9 and Wasip1, the function does nothing, and always returns zero.

func WalkDir added in v0.5.2

func WalkDir(fsys FS, root string, fn WalkDirFunc) error

WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.

All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.

The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.

WalkDir does not follow symbolic links found in directories, but if root itself is a symbolic link, its target will be walked.

func WriteFile added in v0.4.1

func WriteFile(name string, data []byte, perm os.FileMode, opts ...Option) error

WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it using perm's permissions bits (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state. Use WriteFile() with the WithAtomicity(true) option, if this is a concern.

When WithAtomicity(true) is passed, WriteFile atomically writes the contents of data to the specified filename. The target file is guaranteed to be either fully written, or not written at all. WriteFile overwrites any file that exists at the location (but only if the write fully succeeds, otherwise the existing file is unmodified).

If perm is zero, then 0o666 is used, as this is what the os.Create() function uses. If both perm, and WithFileMode(perm) are provided, WithFileMode(perm) takes precedence.

Additional option arguments can be used to change the default configuration for the target file.

On Plan 9, atomic creation of a new file is supported, but atomic replacement of an existing file is not. If the destination exists, WriteFile returns an error matching errors.ErrUnsupported and leaves the destination unchanged. To work around this issue, use the WithNonAtomicReplace option.

func WriteFileAtomic deprecated added in v0.4.2

func WriteFileAtomic(filename string, data []byte, fns ...Option) error

WriteFileAtomic atomically writes the contents of data to the specified filename. The target file is guaranteed to be either fully written, or not written at all. WriteFileAtomic overwrites any file that exists at the location (but only if the write fully succeeds, otherwise the existing file is unmodified). Additional option arguments can be used to change the default configuration for the target file.

Deprecated: Use WriteFile() with WithAtomicity(true) instead.

This function will be removed in a future release.

func WriteReader added in v0.5.5

func WriteReader(name string, reader io.Reader, perm os.FileMode, fns ...Option) (err error)

WriteReader writes r to the named file, creating it if necessary. If the file does not exist, WriteReader creates it using perm's permissions bits (before umask); otherwise WriteReader truncates it before writing, without changing permissions. Since WriteReader requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state. Use WriteReader() with the WithAtomicity(true) options, if this is a concern.

When WithAtomicity(true) is passed, WriteReader atomically writes the contents of r to the specified filename. The target file is guaranteed to be either fully written, or not written at all. WriteReader overwrites any file that exists at the location (but only if the write fully succeeds, otherwise the existing file is unmodified).

If perm is zero, then 0o666 is used, as this is what the os.Create() function uses. If both perm, and WithFileMode(perm) are provided, WithFileMode(perm) takes precedence.

Additional option arguments can be used to change the default configuration for the target file.

On Plan 9, atomic creation of a new file is supported, but atomic replacement of an existing file is not. If the destination exists, WriteReader returns an error matching errors.ErrUnsupported and leaves the destination unchanged. To work around this issue, use the WithNonAtomicReplace option.

func WriteReaderAtomic deprecated added in v0.4.2

func WriteReaderAtomic(filename string, r io.Reader, fns ...Option) error

WriteReaderAtomic atomically writes the contents of r to the specified filename. The target file is guaranteed to be either fully written, or not written at all. WriteReaderAtomic overwrites any file that exists at the location (but only if the write fully succeeds, otherwise the existing file is unmodified). Additional option arguments can be used to change the default configuration for the target file.

Deprecated: Use WriteReader() with WithAtomicity(true) instead.

This function will be removed in a future release.

Types

type DirEntry added in v0.5.2

type DirEntry interface {
	// Name returns the name of the file (or subdirectory) described by the entry.
	// This name is only the final element of the path (the base name), not the entire path.
	// For example, Name would return "hello.go" not "home/gopher/hello.go".
	Name() string

	// IsDir reports whether the entry describes a directory.
	IsDir() bool

	// Type returns the type bits for the entry.
	// The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
	Type() os.FileMode

	// Info returns the FileInfo for the file or subdirectory described by the entry.
	// The returned FileInfo may be from the time of the original directory read
	// or from the time of the call to Info. If the file has been removed or renamed
	// since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
	// If the entry denotes a symbolic link, Info reports the information about the link itself,
	// not the link's target.
	Info() (FileInfo, error)
}

A DirEntry is an entry read from a directory (using the ReadDir function or a [ReadDirFile]'s ReadDir method).

func FileInfoToDirEntry added in v0.5.2

func FileInfoToDirEntry(info FileInfo, parent string) DirEntry

FileInfoToDirEntry returns a DirEntry that returns information from info. If info is nil, FileInfoToDirEntry returns nil.

func ReadDir added in v0.5.2

func ReadDir(name string) ([]DirEntry, error)

ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.

type FS added in v0.5.2

type FS = fs.FS

type FileInfo

type FileInfo interface {
	fs.FileInfo

	ATime() time.Time // last accessed time, or 0 if unsupported
	BTime() time.Time // created (birthed) time, or 0 if unsupported
	CTime() time.Time // status/metadata changed time, or 0 if unsupported
	// MTime() time.Time    // last modified time (alias)
	Links() uint         // number of hard links, or 0 if unsupported
	UID() int            // user ID, or -1 if an error or unsupported
	GID() int            // group ID, or -1 if an error or unsupported
	User() string        // user name, or "" if an error or unsupported
	Group() string       // group name, or "" if an error or unsupported
	PartitionID() uint64 // unique disk partition ID
	FileID() uint64      // unique file ID (on a specific partition)
	Error() error        // error result of the last system call that failed
	String() string
}

A FileInfo describes a file and is returned by Stat. See https://github.com/golang/go/blob/ad7a6f81/src/io/fs/fs.go#L158

func Fstat added in v0.5.4

func Fstat(f *os.File) (FileInfo, error)

Fstat returns a FileInfo structure describing file. If there is an error, it will be of type *PathError.

func Lstat

func Lstat(name string) (FileInfo, error)

Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type [*PathError].

On Windows, if the file is a reparse point that is a surrogate for another named entity (such as a symbolic link or mounted folder), the returned FileInfo describes the reparse point, and makes no attempt to resolve it.

func Stat

func Stat(name string) (FileInfo, error)

Stat returns a FileInfo describing the named file. If there is an error, it will be of type [*PathError].

type FileMode added in v0.4.2

type FileMode = os.FileMode

A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is [ModeDir] for directories.

type Option added in v0.4.2

type Option func(*options)

Option functions modify Options.

func GetOptions added in v0.5.6

func GetOptions() []Option

func WithAtomicity added in v0.5.5

func WithAtomicity(atomically bool) Option

WithAtomicity creates or renames a file atomically. Used by the WriteFile and WriteReader functions.

func WithDefaultFileMode added in v0.5.2

func WithDefaultFileMode(mode os.FileMode) Option

WithDefaultFileMode sets the default file mode instead of using the `os.CreateTemp()` default of `0600`. Used by the WriteFile and WriteReader functions.

func WithDeleteOnClose added in v0.5.7

func WithDeleteOnClose(deleteOnClose bool) Option

WithDeleteOnClose deletes the file when the file is closed. Used by the Create, CreateTemp, Open and OpenFile functions.

func WithFileMode added in v0.5.2

func WithFileMode(mode os.FileMode) Option

WithFileMode sets the file mode to the desired value and has precedence over all other options. Used by the Create, CreateTemp, MkdirTemp, Open, OpenFile, WriteFile, and WriteReader functions.

func WithFlags deprecated added in v0.5.2

func WithFlags(flags int) Option

WithFlags sets the flag option. Used by the Create, Open, OpenFile, WriteFile, and WriteReader functions.

Deprecated: Use WithOpenFlags() instead.

This function will be removed in a future release.

func WithKeepFileMode added in v0.5.2

func WithKeepFileMode(keep bool) Option

WithKeepFileMode preserves the file mode of an existing file instead of using the default value. Used by the WriteFile and WriteReader functions.

func WithNonAtomicReplace added in v0.5.6

func WithNonAtomicReplace(nonAtomicReplace bool) Option

WithNonAtomicReplace permits a non-atomic replacement when the operating system cannot atomically replace an existing destination.

On Plan 9, this may temporarily leave the destination absent. The default is false.

func WithOpenFlags added in v0.5.7

func WithOpenFlags(openFlags int) Option

WithOpenFlags sets the openFlags option. Used by the Create, Open, OpenFile, WriteFile, and WriteReader functions.

func WithReadOnlyMode added in v0.5.2

func WithReadOnlyMode(mode ReadOnlyMode) Option

WithReadOnlyMode is used to determine if/when to set a file's read-only (RO) attribute. The following values are supported: ReadOnlyModeIgnore do not set a file's RO attribute, and ignore if it's set. ReadOnlyModeFromPermissions set a file's RO attribute if the file's FileMode has the user writable bit set. ReadOnlyModeClear do not set a file's RO attribute, and if it's set, reset it. The option is functional on Windows only. On other OSes, it is ignored. Used by the Chmod, Create, CreateTemp, Fchmod, Open, OpenFile, WriteFile, and WriteReader functions.

func WithRetrySeconds deprecated added in v0.5.4

func WithRetrySeconds(seconds float64) Option

WithRetrySeconds sets the retry timeout option in seconds. The default is 0 which means to not retry at all. Used by the Rename and RemoveAll functions.

Deprecated: Use WithRetryTimeout() instead.

This function will be removed in a future release.

func WithRetryTimeout added in v0.5.7

func WithRetryTimeout(timeout time.Duration) Option

WithRetryTimeout sets the retry timeout option in seconds. The default is time.Zero() which means to not retry at all. Used by the Rename and RemoveAll functions.

func WithSetSymlinkOwner added in v0.5.2

func WithSetSymlinkOwner(setSymlinkOwner bool) Option

WithSetSymlinkOwner sets the symlink's owner to be the current user. Otherwise, the symlink will have a default owner assigned by the system, such as BUILTIN\Administrator. The option is functional on Windows only. On other OSes, it is ignored. Used by the Symlink function.

func WithSkipACLs added in v0.5.7

func WithSkipACLs(skipACLs bool) Option

WithSkipACLs skips setting ACLs (Access Control Lists) on Windows. The option is functional on Windows only. On other OSes, it is ignored. Used by the Chmod function.

type ReadOnlyMode added in v0.5.2

type ReadOnlyMode int

ReadOnlyMode defines how to handle a file's read-only attribute on Windows.

const (
	// ReadOnlyModeIgnore does not set a file's read-only attribute, and ignores
	// if it's set (Windows only).
	ReadOnlyModeIgnore ReadOnlyMode = 0 + iota
	// ReadOnlyModeFromPermissions set a file's read-only attribute, if the
	// specified perm FileMode has the user writable bit (0o200) set. Otherwise,
	// it clears (resets) it. (Windows only).
	ReadOnlyModeFromPermissions
	// ReadOnlyModeClear does not set a file's read-only attribute, and if it's
	// set, it clears (resets) it. (Windows only).
	ReadOnlyModeClear
)

type UserIDSourceType added in v0.5.0

type UserIDSourceType uint

UserIDSourceType defines if the underlying source for the user's ID, is an int (UID() function), or a string (User() function).

const (
	// UserIDSourceUnknown is unused.
	UserIDSourceUnknown UserIDSourceType = iota
	// UserIDSourceIsInteger defines if the OS uses an int to identify the user.
	UserIDSourceIsInteger
	// UserIDSourceIsString defines if the OS uses a string to identify the
	// user.
	UserIDSourceIsString
	// UserIDSourceIsSID defines if the OS uses a SID to identify the user.
	UserIDSourceIsSID
	// UserIDSourceIsNone defines if the OS does not provide user's IDs, so
	// we provide sane defaults instead.
	UserIDSourceIsNone
)

func UserIDSource added in v0.5.0

func UserIDSource() UserIDSourceType

UserIDSource returns the source of the user's ID: UserIDSourceIsInt, UserIDSourceIsString, or UserIDSourceIsNone.

type WalkDirFunc added in v0.5.2

type WalkDirFunc func(path string, d DirEntry, err error) error

WalkDirFunc is the type of the function called by WalkDir to visit each file or directory.

The path argument contains the argument to WalkDir as a prefix. That is, if WalkDir is called with root argument "dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a".

The d argument is the DirEntry for the named path.

The error result returned by the function controls how WalkDir continues. If the function returns the special value SkipDir, WalkDir skips the current directory (path if d.IsDir() is true, otherwise path's parent directory). If the function returns the special value SkipAll, WalkDir skips all remaining files and directories. Otherwise, if the function returns a non-nil error, WalkDir stops entirely and returns that error.

The err argument reports an error related to path, signaling that WalkDir will not walk into that directory. The function can decide how to handle that error; as described earlier, returning the error will cause WalkDir to stop walking the entire tree.

WalkDir calls the function with a non-nil err argument in two cases.

First, if the initial Stat on the root directory fails, WalkDir calls the function with path set to root, d set to nil, and err set to the error from fs.Stat.

Second, if a directory's ReadDir method (see [ReadDirFile]) fails, WalkDir calls the function with path set to the directory's path, d set to an DirEntry describing the directory, and err set to the error from ReadDir. In this second case, the function is called twice with the path of the directory: the first call is before the directory read is attempted and has err set to nil, giving the function a chance to return SkipDir or SkipAll and avoid the ReadDir entirely. The second call is after a failed ReadDir and reports the error from ReadDir. (If ReadDir succeeds, there is no second call.)

The differences between WalkDirFunc compared to path/filepath.WalkFunc are:

  • The second argument has type DirEntry instead of FileInfo.
  • The function is called before reading a directory, to allow SkipDir or SkipAll to bypass the directory read entirely or skip all remaining files and directories respectively.
  • If a directory read fails, the function is called a second time for that directory to report the error.

Directories

Path Synopsis
cmd
demo command
demo is a sample application that runs functions provided by this library.
demo is a sample application that runs functions provided by this library.
hasperms command
parttest command
probe command
updater command
package updater checks if there are any updates to snippetted code, and provides diffs of any changes found.
package updater checks if there are any updates to snippetted code, and provides diffs of any changes found.
volinfo command
volinfo retrieves information about volumes (partitions).
volinfo retrieves information about volumes (partitions).
syscall/windows/registry
Package registry provides access to the Windows registry.
Package registry provides access to the Windows registry.
syscall/windows/sysdll
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself.
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself.
Package robustio wraps I/O functions that are prone to failure on Windows, transparently retrying errors up to an arbitrary timeout.
Package robustio wraps I/O functions that are prone to failure on Windows, transparently retrying errors up to an arbitrary timeout.

Jump to

Keyboard shortcuts

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