fileutil

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package fileutil provides file system operations with proper error handling.

All functions in this package follow Go best practices: - Return errors instead of panicking - Accept context.Context for cancellable operations - Close resources properly using defer

Reading Files

Functions for reading file contents:

lines, err := fileutil.ReadLines(ctx, "file.txt")
content, err := fileutil.ReadString(ctx, "file.txt")
data, err := fileutil.ReadBytes(ctx, "file.txt")

File Information

Functions for checking file properties:

if fileutil.Exists(path) { ... }
if fileutil.IsDir(path) { ... }
size, err := fileutil.Size(path)
modTime, err := fileutil.ModTime(path)

Directory Operations

Functions for working with directories:

files, err := fileutil.List(ctx, dir, fileutil.Recursive)
files, err := fileutil.Find(ctx, dir, "*.go")
err := fileutil.EnsureDir(path, 0755)

Line Terminator Handling

Functions for handling different line endings:

terminator := fileutil.DetectLineTerminator(data)
normalized := fileutil.NormalizeLineTerminators(data, fileutil.LF)

Context Support

Long-running operations accept context.Context for cancellation:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
lines, err := fileutil.ReadLines(ctx, "large-file.txt")

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFile      = errors.New("path is not a file")
	ErrNotDir       = errors.New("path is not a directory")
	ErrNotExist     = errors.New("path does not exist")
	ErrReadCanceled = errors.New("read operation canceled")
)

Common errors.

Functions

func Abs

func Abs(path string) string

Abs returns the absolute path. Returns the path unchanged if it's already absolute or on error.

func AppendBytes

func AppendBytes(path string, data []byte, perm fs.FileMode) error

AppendBytes appends data to a file, creating it if necessary.

func AppendLine

func AppendLine(path, line string, terminator LineTerminator, perm fs.FileMode) error

AppendLine appends a line to a file with the specified terminator.

func AppendString

func AppendString(path, content string, perm fs.FileMode) error

AppendString appends a string to a file.

func Base

func Base(path string) string

Base returns the last element of the path.

func BaseName

func BaseName(path string) string

BaseName returns the file name without extension.

func Clean

func Clean(path string) string

Clean returns the cleaned path.

func Copy

func Copy(ctx context.Context, src, dst string) error

Copy copies a file from src to dst. Creates destination directory if needed.

func CountLines

func CountLines(ctx context.Context, path string) (int, error)

CountLines counts the number of lines in a file. More memory-efficient than ReadLines for large files.

func Dir

func Dir(path string) string

Dir returns the directory component of the path.

func DirSize

func DirSize(ctx context.Context, dir string) (int64, error)

DirSize calculates the total size of a directory and its contents.

func EnsureDir

func EnsureDir(path string, perm fs.FileMode) error

EnsureDir creates a directory if it doesn't exist. Creates parent directories as needed (like mkdir -p).

func Exists

func Exists(path string) bool

Exists reports whether the path exists.

func Extension

func Extension(path string) string

Extension returns the file extension including the dot. Returns empty string if no extension.

func Find

func Find(ctx context.Context, dir, pattern string) ([]string, error)

Find returns files matching the glob pattern. Pattern syntax follows filepath.Match.

func FindByExtension

func FindByExtension(ctx context.Context, dir, ext string) ([]string, error)

FindByExtension returns files with the specified extension. Extension should include the dot (e.g., ".go").

func IsDir

func IsDir(path string) bool

IsDir reports whether the path is a directory.

func IsEmpty

func IsEmpty(path string) (bool, error)

IsEmpty reports whether the file or directory is empty. For files, returns true if size is 0. For directories, returns true if no entries exist.

func IsExecutable

func IsExecutable(path string) bool

IsExecutable reports whether the path is executable.

func IsFile

func IsFile(path string) bool

IsFile reports whether the path is a regular file.

func IsSymlink(path string) bool

IsSymlink reports whether the path is a symbolic link.

func Join

func Join(elem ...string) string

Join joins path elements.

func List

func List(ctx context.Context, dir string, opts ListOption) ([]string, error)

List returns entries in a directory. Use ListOption flags to control behavior.

func ModTime

func ModTime(path string) (time.Time, error)

ModTime returns the modification time of the file.

func Mode

func Mode(path string) (fs.FileMode, error)

Mode returns the file mode of the path.

func Move

func Move(ctx context.Context, src, dst string) error

Move moves a file from src to dst. Attempts rename first, falls back to copy+delete.

func NormalizeLineTerminators

func NormalizeLineTerminators(data []byte, target LineTerminator) []byte

NormalizeLineTerminators converts all line terminators to the specified style.

func ReadBytes

func ReadBytes(ctx context.Context, path string) ([]byte, error)

ReadBytes reads the entire file and returns its contents as bytes. Respects context cancellation before starting the read.

func ReadLines

func ReadLines(ctx context.Context, path string) ([]string, error)

ReadLines reads the file and returns its contents as a slice of lines. Line terminators are stripped from each line.

func ReadLinesN

func ReadLinesN(ctx context.Context, path string, n int) ([]string, error)

ReadLinesN reads the first n lines from a file. If n <= 0, reads all lines.

func ReadString

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

ReadString reads the entire file and returns its contents as a string.

func Rel

func Rel(base, target string) (string, error)

Rel returns a relative path from base to target.

func SameFile

func SameFile(path1, path2 string) bool

SameFile reports whether fi1 and fi2 describe the same file.

func Size

func Size(path string) (int64, error)

Size returns the size of the file in bytes.

func Split

func Split(path string) (dir, file string)

Split splits a path into directory and file components.

func TempDir

func TempDir(dir, pattern string) (string, error)

TempDir creates a temporary directory and returns its path. The caller is responsible for removing the directory.

func TempFile

func TempFile(dir, pattern string) (string, error)

TempFile creates a temporary file and returns its path. The caller is responsible for removing the file.

func Touch

func Touch(path string) error

Touch creates an empty file or updates its modification time.

func WriteBytes

func WriteBytes(path string, data []byte, perm fs.FileMode) error

WriteBytes writes data to a file, creating it if necessary. Truncates existing files.

func WriteLines

func WriteLines(path string, lines []string, terminator LineTerminator, perm fs.FileMode) error

WriteLines writes lines to a file, joining with the specified terminator.

func WriteString

func WriteString(path, content string, perm fs.FileMode) error

WriteString writes a string to a file.

Types

type LineTerminator

type LineTerminator int

LineTerminator represents different line ending styles.

const (
	// LF represents Unix-style line endings (\n).
	LF LineTerminator = iota
	// CRLF represents Windows-style line endings (\r\n).
	CRLF
	// CR represents old Mac-style line endings (\r).
	CR
	// Mixed indicates the file has inconsistent line endings.
	Mixed
	// Unknown indicates no line endings were found.
	Unknown
)

func DetectFileLineTerminator

func DetectFileLineTerminator(ctx context.Context, path string) (LineTerminator, error)

DetectFileLineTerminator detects line terminator style in a file. Reads only the beginning of the file for efficiency.

func DetectLineTerminator

func DetectLineTerminator(data []byte) LineTerminator

DetectLineTerminator detects the line terminator style in data. Returns Unknown if no line terminators are found. Returns Mixed if multiple styles are detected.

func (LineTerminator) Bytes

func (lt LineTerminator) Bytes() []byte

Bytes returns the byte sequence for the line terminator.

func (LineTerminator) String

func (lt LineTerminator) String() string

String returns the string representation of the line terminator.

type ListOption

type ListOption int

ListOption configures List behavior.

const (
	// FilesOnly lists only files (not directories).
	FilesOnly ListOption = 1 << iota
	// DirsOnly lists only directories (not files).
	DirsOnly
	// Recursive lists contents recursively.
	Recursive
	// IncludeHidden includes hidden files (starting with .)
	IncludeHidden
)

Jump to

Keyboard shortcuts

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