xfs

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 11 Imported by: 0

README

xfs

Cross-platform filesystem utilities with a testable package bridge boundary.

 

This package provides a set of helper functions to resolve paths, inspect filesystem entities, manage files and directories, and obtain standard user directories. It is designed for safe, cross-platform use and isolates external system calls via an internal package bridge for easier unit testing.


Purpose

xfs centralizes common filesystem operations behind a consistent API. It simplifies tasks such as:

  • resolving absolute paths and expanding ~ home directory shortcuts,
  • checking file and directory existence, type and permissions,
  • reading and writing filesystem entries,
  • creating and deleting files and directories,
  • locating standard user directories for config, data, and logs.

The package is built to avoid direct global system calls in business code, favoring a single bridge contract that can be mocked during tests.


Installation

Use go get to add the package to your module:

  go get github.com/AeonDigital/Go-Core/xfs@latest

Import it in your code:

import "github.com/AeonDigital/Go-Core/xfs"

If you also need structured error handling from the repository, import:

import "github.com/AeonDigital/Go-Core/xerrors"

Basic usage

Resolve paths and verify filesystem objects:

path, err := xfs.RetrieveFullPath("~/projects")
if err != nil {
    return err
}

exists := xfs.Exists(path)
isDir := xfs.IsDir(path)

Work with files and directories:

file, err := xfs.CreateFile("~/tmp/example.txt")
if err != nil {
    return err
}
file.Close()

err = xfs.CreateDirPath("~/tmp/nested/config")
if err != nil {
    return err
}

writable := xfs.IsWritable("~/tmp")

Use standard user directories for app-specific storage:

configDir, err := xfs.GetUserConfigDir()
logDir, err := xfs.GetUserLogDir("myapp")

Supported APIs

The package exposes a broad set of filesystem helpers, including:

  • RetrieveFullPath
  • GetUserHomeDir
  • GetUserConfigDir
  • GetUserDataDir
  • GetUserCacheDir
  • GetUserStateDir
  • GetUserRuntimeDir
  • GetUserLogDir
  • GetParentPath
  • Exists
  • IsFile
  • IsDir
  • IsEmptyDir
  • IsReadable
  • IsWritable
  • GetPermission
  • SetPermission
  • CreateFile
  • CreateDir
  • CreateDirPath
  • OpenFileWrite
  • OpenFileRead
  • DeleteFile
  • DeleteDir
  • HasSpaceAvailable
  • GetFileSize
  • IsSameFile

This package uses an internal IPkgBridgeXFS boundary to decouple real OS calls from unit tests and platform-specific behavior.


External dependencies

xfs depends only on the Go standard library and the repository's internal error package:

  • github.com/AeonDigital/Go-Core/xerrors

No third-party external packages are required by this package.

Documentation

Index

Constants

View Source
const (
	XERR_NONE   xerrors.ErrorCode = ""
	XERR_PKGCTX xerrors.ErrorCode = "ERR_XFS"
)

Variables

This section is empty.

Functions

func CopyFile

func CopyFile(pathOrigin string, pathDestiny string) error

CopyFile duplicates the contents of a source file to a destination file. It automatically expands the tilde prefix ("~") on both file paths before execution. It creates the destination file if it does not exist, or opens it in append-mode if it does. Returns nil on success, or an error if path expansion fails, file opening operations are denied, the byte stream transfer fails, or the structural metadata cannot be flushed to disk.

func CreateDir

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

CreateDir creates a single directory at the specified path. It automatically expands the tilde prefix ("~") before creating the folder and fails if the parent directory structure does not exist. An optional os.FileMode can be passed; if omitted, it defaults to standard permissions (0755). Returns nil on success, or an error if path expansion fails or the directory cannot be created.

func CreateDirPath

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

CreateDirPath creates a directory path along with any necessary parent directories. It automatically expands the tilde prefix ("~") before creating the folder structure. An optional os.FileMode can be passed; if omitted, it defaults to standard permissions (0755). If the target path already exists, it does nothing and returns nil.

func CreateFile

func CreateFile(path string, perm ...os.FileMode) (*os.File, error)

CreateFile creates a new file at the specified path, truncating it if it already exists. It automatically expands the tilde prefix ("~") before executing the operation. An optional os.FileMode can be passed; if omitted, it defaults to standard system permissions (0666). Returns a pointer to the opened file object (*os.File) ready for writing, or an error if path expansion or file creation fails.

func DeleteDir

func DeleteDir(path string, recursive bool) error

DeleteDir removes a directory at the specified path, with optional recursive deletion of all its contents. It automatically expands the tilde prefix ("~") before executing any filesystem validation or removal steps. If recursive is true, it uses os.RemoveAll to forcefully delete the folder and everything inside it; otherwise, it uses os.Remove and fails if the directory is not completely empty. Returns nil on success, or an error if path expansion fails, the path is not a directory, or the system removal operation is denied.

func DeleteFile

func DeleteFile(path string) error

DeleteFile removes a regular file at the specified path. It automatically expands the tilde prefix ("~") before performing the check and deletion. It explicitly fails if the targeted path is a directory to prevent accidental directory structural loss. Returns nil on success, or an error if path expansion fails, the path points to a directory, or the system removal operation is denied.

func Exists

func Exists(path string) bool

Exists checks if a file or directory exists at the given path. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before executing the check. Returns true if the target path is found on the system, or false if it does not exist or if path expansion fails.

func ExportSetStatfsFunc

func ExportSetStatfsFunc(fn func(string, interface{}) error) func()

ExportSetStatfsFunc allows tests to replace the underlying statfs implementation. The function accepts a callback with signature func(path string, buf interface{}) error where buf will be a *unix.Statfs_t. It returns a restore function.

func GetFileSize

func GetFileSize(path string) (int64, error)

GetFileSize returns the size of the file in bytes at the specified path. It automatically expands the tilde prefix ("~") before checking the path. It explicitly returns an error if the path points to a directory or if the file does not exist. Returns the file size in bytes as an int64, or an error if path expansion, system calls, or validations fail.

func GetParentPath

func GetParentPath(path string) (string, error)

GetParentPath extracts and returns the parent directory path from a given file path. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before isolating the layout. Returns the parent directory string, or an empty string if the input path is empty or if path expansion fails.

func GetPermission

func GetPermission(path string) (os.FileMode, error)

GetPermission retrieves the system permission bits (os.FileMode) for the specified file or directory. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before executing the check. Returns the file mode permissions, or an error if path expansion fails or if the path does not exist.

func GetUserCacheDir

func GetUserCacheDir() (string, error)

GetUserCacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that.

On Unix systems, it returns $XDG_CACHE_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it returns $HOME/Library/Caches. On Windows, it returns %LocalAppData%. On Plan 9, it returns $home/lib/cache.

If the location cannot be determined (for example, $HOME is not defined) or the path in $XDG_CACHE_HOME is relative, then it will return an error.

func GetUserConfigDir

func GetUserConfigDir() (string, error)

GetUserConfigDir returns the default root directory to use for user-specific configuration data. Users should create their own application-specific subdirectory within this one and use that.

On Unix systems, it returns $XDG_CONFIG_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.config. On Darwin, it returns $HOME/Library/Application Support. On Windows, it returns %AppData%. On Plan 9, it returns $home/lib.

If the location cannot be determined (for example, $HOME is not defined) or the path in $XDG_CONFIG_HOME is relative, then it will return an error.

func GetUserDataDir

func GetUserDataDir() (string, error)

GetUserDataDir resolves the standard, platform-specific directory for persisting application data, strictly adhering to OS ecosystem conventions and specifications.

Behavior by platform:

  • Windows: Prioritizes the "%LOCALAPPDATA%\Data" environment variable path. Falls back to "AppData\Local\Data" relative to the user's home directory if unset.
  • Darwin (macOS): Returns the standard "Library/Application Support" directory as mandated by Apple's File System guidelines.
  • Linux/Other: Strictly follows the XDG Base Directory Specification. It queries "$XDG_DATA_HOME" and falls back to the default "~/.local/share" directory.

It returns the absolute path without creating the directory on the file system. An error is returned if the user's home directory cannot be resolved.

func GetUserHomeDir

func GetUserHomeDir() (string, error)

GetUserHomeDir returns the current user's home directory.

On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable.

If the expected variable is not set in the environment, UserHomeDir returns either a platform-specific default value or a non-nil error.

func GetUserLogDir

func GetUserLogDir() (string, error)

GetUserLogDir resolves the standard, platform-specific directory for storing application log files, ensuring compliance with each operating system's logging conventions.

Behavior by platform:

  • Windows: Appends a "Logs" subdirectory to the "%LOCALAPPDATA%" environment path. Falls back to "AppData\Local\Logs" relative to the user's home directory if unset.
  • Darwin (macOS): Returns the standard user-specific logging directory "~/Library/Logs" as defined by Apple's diagnostics and logging architecture.
  • Linux/Other: Follows modern XDG extensions. It queries "$XDG_STATE_HOME" (falling back to "~/.local/state") as the primary logging path, and checks "$XDG_CACHE_HOME" ("~/.cache") as a secondary fallback.

It returns the absolute path without creating the directory on the file system. An error is returned if the user's home directory cannot be resolved.

func GetUserRuntimeDir

func GetUserRuntimeDir() (string, error)

GetUserRuntimeDir resolves the standard, platform-specific directory for storing ephemeral runtime files, such as sockets, named pipes, process locks, or volatile session configs.

Behavior by platform:

  • Windows: Appends a "Runtime" subdirectory to the "%LOCALAPPDATA%" environment path. Falls back to "AppData\Local\Runtime" relative to the user's home directory if unset.
  • Darwin (macOS): Defaults to the OS-managed transient directory returned by os.TempDir(), suffixed with the application namespace, to match macOS ephemeral data policies.
  • Linux/Other: Strictly follows the XDG Base Directory Specification. It queries "$XDG_RUNTIME_DIR" and falls back to the system's global temporary path via os.TempDir() if unset.

It returns the absolute path without creating the directory on the file system. An error is returned if the user's home directory cannot be resolved.

func GetUserStateDir

func GetUserStateDir() (string, error)

GetUserStateDir resolves the standard, platform-specific directory for storing application state files, such as history, current session data, and non-critical logs.

Behavior by platform:

  • Windows: Prioritizes the "%LOCALAPPDATA%\State" environment variable path. Falls back to "AppData\Local\State" relative to the user's home directory if unset.
  • Darwin (macOS): Returns the standard "Library/Application Support" directory, aligning state persistence with Apple's bundle state and data conventions.
  • Linux/Other: Strictly follows the XDG Base Directory Specification. It queries "$XDG_STATE_HOME" and falls back to the default "~/.local/state" directory.

It returns the absolute path without creating the directory on the file system. An error is returned if the user's home directory cannot be resolved.

func GetVolumeFreeSpace

func GetVolumeFreeSpace(currentPath string, requiredBytes uint64) (bool, error)

GetVolumeFreeSpace calculates the available storage space on Linux, FreeBSD, or Dragonfly systems. It executes a native unix.Statfs system call to resolve active blocks and volume geometry.

func HasSpaceAvailable

func HasSpaceAvailable(path string, requiredBytes uint64) (bool, error)

HasSpaceAvailable checks if the storage volume containing the specified path has at least the required number of bytes free. It accepts a filesystem path (path) and the minimum required space in bytes (requiredBytes). If the target path does not exist, it traverses upward to find the closest existing parent directory to accurately target the underlying volume. Returns true if the volume has sufficient space available for the current user, or false along with an error if the path expansion, UTF-16 conversion, or Win32 GetDiskFreeSpaceEx API call fails.

func IsDir

func IsDir(path string) bool

IsDir checks if the specified path exists and points to a directory. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before executing the check. Returns true if the path is a directory, or false if it does not exist, is a regular file/symlink, or if system calls fail.

func IsEmptyDir

func IsEmptyDir(path string) (bool, error)

IsEmptyDir checks if the specified directory exists and contains no files or subdirectories. It automatically expands the tilde prefix ("~") before evaluating the target directory path. Returns true if the directory is completely empty, or false along with an error if the path does not exist, is not a directory, or if read permissions are denied.

func IsFile

func IsFile(path string) bool

IsFile checks if the specified path exists and points to a regular file. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before executing the check. Returns true if the path is a regular file, or false if it does not exist, is a directory/symlink, or if system calls fail.

func IsFileDirExists

func IsFileDirExists(filePath string) bool

IsFileDirExists extracts the parent directory path from a given file path and checks if it exists as a valid directory. It automatically expands the tilde prefix ("~") before isolating the parent directory layout. Returns true if the parent directory structure exists on the system, or false if the path is empty, expansion fails, or the directory does not exist.

func IsReadable

func IsReadable(path string) bool

IsReadable checks if the current application process has sufficient permissions to read the file or directory at the specified path. It automatically expands the tilde prefix ("~") and robustly handles both regular files and directory permission boundaries across different operating systems. Returns true if the path can be successfully read, or false if permissions are denied or if the path does not exist.

func IsSameFile

func IsSameFile(pathA, pathB string) (bool, error)

IsSameFile checks if two different paths point to the exact same physical file or directory on the storage device. It automatically expands the tilde prefix ("~") on both inputs and resolves any symbolic links encountered. It relies on Go's native os.SameFile mechanism to compare low-level system identities like inodes or file IDs. Returns true if both paths target the identical filesystem resource, or false along with an error if metadata retrieval fails.

func IsWritable

func IsWritable(path string) bool

IsWritable checks if the current application process has sufficient permissions to modify or write to the file or directory at the specified path. It automatically expands the tilde prefix ("~") and tests directories by attempting to create a temporary file inside them, or files by opening them in write-only append mode. Returns true if the path can be written to, or false if permissions are denied, if the path does not exist, or if the test operations fail.

func OpenFileRead

func OpenFileRead(path string) (*os.File, error)

OpenFileRead opens an existing file exclusively in read-only mode. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before attempting to open the path. Returns a pointer to the opened file object (*os.File) ready for reading, or an error if path expansion fails or if the file does not exist.

func OpenFileWrite

func OpenFileWrite(path string, truncate bool, perm ...os.FileMode) (*os.File, error)

OpenFileWrite opens a file for writing, creating it with the specified or default permissions (0644) if it does not exist. It automatically expands the tilde prefix ("~") before opening the path. If truncate is true, the file's existing content is cleared upon opening; otherwise, new data is appended to the end. An optional os.FileMode can be passed to override the default creation permissions. Returns a pointer to the opened file object (*os.File) ready for writing, or an error if path expansion or file opening fails.

func RetrieveFullPath

func RetrieveFullPath(path string) (string, error)

RetrieveFullPath returns the fully resolved absolute path, or an error if system paths cannot be determined.

Replaces the tilde prefix ("~") with the user's home directory and strictly resolves the final result into a clean, absolute filesystem path. If the path is relative, it anchors it to the current working directory, removing any redundancies like "." or "..".

func SetPermission

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

SetPermission updates the filesystem permission bits (os.FileMode) for the specified file or directory. It automatically expands the tilde prefix ("~") using the RetrieveFullPath function before applying the changes. Returns nil on success, or an error if path expansion fails, the path does not exist, or the operation is denied.

Types

type IPkgBridgeXFS

type IPkgBridgeXFS interface {
	FilepathAbs(path string) (string, error)
	RetrieveFullPath(path string) (string, error)

	GetUserHomeDir() (string, error)
	GetUserConfigDir() (string, error)
	GetUserDataDir() (string, error)
	GetUserCacheDir() (string, error)
	GetUserStateDir() (string, error)
	GetUserRuntimeDir() (string, error)
	GetUserLogDir() (string, error)

	// GROUP: EXISTENCE AND TYPES
	ReadDir(f *os.File, n int) ([]fs.DirEntry, error)

	IsDir(path string) bool
	Exists(path string) bool

	// GROUP : NATIVE OS
	OsStat(name string) (os.FileInfo, error)
	OsOpen(name string) (*os.File, error)
	//OSUserDataDir(home string, appName string) string
	//OSUserLogDir(home string, appName string) string
	OsOpenFile(name string, flag int, perm os.FileMode) (*os.File, error)
	OsCreateTemp(dir, pattern string) (*os.File, error)
	OsRemove(name string) error
	OsRemoveAll(path string) error
	OsChmod(name string, mode os.FileMode) error
	OsMkdir(name string, perm os.FileMode) error
	OsMkdirAll(path string, perm os.FileMode) error

	GetVolumeFreeSpace(currentPath string, requiredBytes uint64) (bool, error)

	GetRuntimeGOOS() string

	IOCopy(dst io.Writer, src io.Reader) (written int64, err error)
}

IPkgBridgeXFS defines the unified system call and external resource boundary for the xfs package. It consolidates all direct interactions with the operating system, standard library, and package-level utility functions into a singular, interceptable contract. This architectural decoupling eliminates global state, isolates platform-specific logic, and guarantees thread-safe mocking environments during concurrent black-box execution.

type PkgBridgeXFS

type PkgBridgeXFS struct{}

PkgBridgeXFS serves as the standard, production-ready implementation of IPkgBridgeXFS. It directly maps abstract bridge requests to the Go standard library packages ('os', 'path/filepath') and local package infrastructure, routing calls natively without intermediate overhead or stateful transformations.

func (PkgBridgeXFS) Exists

func (PkgBridgeXFS) Exists(path string) bool

func (PkgBridgeXFS) FilepathAbs

func (PkgBridgeXFS) FilepathAbs(path string) (string, error)

func (PkgBridgeXFS) GetParentPath

func (PkgBridgeXFS) GetParentPath(path string) (string, error)

func (PkgBridgeXFS) GetRuntimeGOOS

func (PkgBridgeXFS) GetRuntimeGOOS() string

func (PkgBridgeXFS) GetUserCacheDir

func (PkgBridgeXFS) GetUserCacheDir() (string, error)

func (PkgBridgeXFS) GetUserConfigDir

func (PkgBridgeXFS) GetUserConfigDir() (string, error)

func (PkgBridgeXFS) GetUserDataDir

func (PkgBridgeXFS) GetUserDataDir() (string, error)

func (PkgBridgeXFS) GetUserHomeDir

func (PkgBridgeXFS) GetUserHomeDir() (string, error)

func (PkgBridgeXFS) GetUserLogDir

func (PkgBridgeXFS) GetUserLogDir() (string, error)

func (PkgBridgeXFS) GetUserRuntimeDir

func (PkgBridgeXFS) GetUserRuntimeDir() (string, error)

func (PkgBridgeXFS) GetUserStateDir

func (PkgBridgeXFS) GetUserStateDir() (string, error)

func (PkgBridgeXFS) GetVolumeFreeSpace

func (PkgBridgeXFS) GetVolumeFreeSpace(currentPath string, requiredBytes uint64) (bool, error)

func (PkgBridgeXFS) IOCopy

func (PkgBridgeXFS) IOCopy(dst io.Writer, src io.Reader) (written int64, err error)

func (PkgBridgeXFS) IsDir

func (PkgBridgeXFS) IsDir(path string) bool

func (PkgBridgeXFS) OsChmod

func (PkgBridgeXFS) OsChmod(name string, mode os.FileMode) error

func (PkgBridgeXFS) OsCreateTemp

func (PkgBridgeXFS) OsCreateTemp(dir, pattern string) (*os.File, error)

func (PkgBridgeXFS) OsMkdir

func (PkgBridgeXFS) OsMkdir(name string, perm os.FileMode) error

func (PkgBridgeXFS) OsMkdirAll

func (PkgBridgeXFS) OsMkdirAll(path string, perm os.FileMode) error

func (PkgBridgeXFS) OsOpen

func (PkgBridgeXFS) OsOpen(name string) (*os.File, error)

func (PkgBridgeXFS) OsOpenFile

func (PkgBridgeXFS) OsOpenFile(name string, flag int, perm os.FileMode) (*os.File, error)

func (PkgBridgeXFS) OsRemove

func (PkgBridgeXFS) OsRemove(name string) error

func (PkgBridgeXFS) OsRemoveAll

func (PkgBridgeXFS) OsRemoveAll(path string) error

func (PkgBridgeXFS) OsStat

func (PkgBridgeXFS) OsStat(name string) (os.FileInfo, error)

func (PkgBridgeXFS) ReadDir

func (PkgBridgeXFS) ReadDir(f *os.File, n int) ([]fs.DirEntry, error)

func (PkgBridgeXFS) RetrieveFullPath

func (PkgBridgeXFS) RetrieveFullPath(path string) (string, error)

Jump to

Keyboard shortcuts

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