fileutil

package
v1.30.3 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: GPL-3.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxSafeNameLength is the maximum length of a safe filename
	MaxSafeNameLength = 100
)

Variables

View Source
var (
	ErrUnexpectedEOF         = errors.New("unexpected end of input after escape character")
	ErrUnknownEscapeSequence = errors.New("unknown escape sequence")
)

Common errors for file operations

View Source
var ValidYAMLExtensions = []string{yamlExtension, ymlExtension}

ValidYAMLExtensions contains valid YAML extensions.

Functions

func DecodeString added in v1.26.0

func DecodeString(charset string, data []byte) string

DecodeString decodes a byte slice using the specified character encoding. If the encoding is empty, UTF-8, or unknown, the bytes are returned as-is. This function is useful for converting log output from non-UTF-8 encodings (such as Shift_JIS, EUC-JP, etc.) to UTF-8 strings.

func EnsureYAMLExtension

func EnsureYAMLExtension(filename string) string

EnsureYAMLExtension adds .yaml extension if not present if it has .yml extension, replace it with .yaml

func FileExists

func FileExists(file string) bool

FileExists reports whether the named file exists. It returns false if os.Stat reports the file does not exist and true otherwise (including when os.Stat returns a different error).

func IsDir

func IsDir(path string) bool

IsDir returns true if path is a directory.

func IsFile added in v1.25.0

func IsFile(path string) bool

IsFile reports whether the named path exists and is a regular file. It returns false if the path does not exist or if an error occurs while obtaining file info.

func IsFileWithExtension

func IsFileWithExtension(filename string, validExtensions []string) bool

IsFileWithExtension is a more generic function that checks if a file has any of the provided extensions.

func IsYAMLFile

func IsYAMLFile(filename string) bool

IsYAMLFile checks if a file has a valid YAML extension (.yaml or .yml). Returns false for empty strings or files without extensions.

func MustGetUserHomeDir

func MustGetUserHomeDir() string

MustGetUserHomeDir returns current working directory. Panics is os.UserHomeDir() returns error

func MustGetwd

func MustGetwd() string

MustGetwd returns current working directory. Panics is os.Getwd() returns error

func MustTempDir

func MustTempDir(pattern string) string

MustTempDir returns temporary directory. This function is used only for testing.

func OpenOrCreateFile

func OpenOrCreateFile(filepath string) (*os.File, error)

OpenOrCreateFile opens (or creates) the log file with flags for creation, write-only access, OpenOrCreateFile opens or creates the named file for appending with synchronous I/O and sets permissions to 0600. It returns the opened *os.File or a non-nil error if the operation fails.

func ReadLogContent

func ReadLogContent(filePath string, options LogReadOptions) (string, int, int, bool, bool, error)

ReadLogContent reads a specific portion of a log file and returns it as a string nolint:revive

func ResolvePath

func ResolvePath(path string) (string, error)

ResolvePath resolves a path to an absolute path. It handles empty paths, tilde expansion, environment variables, and converts to an absolute path.

func ResolvePathOrBlank

func ResolvePathOrBlank(path string) string

ResolvePathOrBlank works like ResolvePath but panics on error. Useful when you're confident the path resolution will succeed.

func SafeName

func SafeName(str string) string

SafeName converts a string to a safe filename containing only alphanumeric characters, underscores, and hyphens

func TrimYAMLFileExtension

func TrimYAMLFileExtension(filename string) string

TrimYAMLFileExtension trims the .yml or .yaml extension from a filename.

func TruncString

func TruncString(val string, max int) string

TruncString TurnString returns truncated string.

Types

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache implements a generic file caching mechanism with TTL-based expiration. It stores entries with metadata like size and modification time to detect changes. TODO: Consider replacing this with hashicorp/golang-lru for better performance https://github.com/hashicorp/golang-lru

func NewCache

func NewCache[T any](name string, cap int, ttl time.Duration) *Cache[T]

NewCache creates a new cache with the specified capacity and time-to-live duration

func (*Cache[T]) Entry

func (c *Cache[T]) Entry(fileName string) Entry[T]

Entry returns the cached entry for a file, or an empty entry if not found

func (*Cache[T]) Invalidate

func (c *Cache[T]) Invalidate(fileName string)

Invalidate removes an item from the cache

func (*Cache[T]) IsStale

func (*Cache[T]) IsStale(
	fileName string, entry Entry[T],
) (bool, os.FileInfo, error)

IsStale checks if a cached entry is stale compared to the file on disk by comparing modification time and size

func (*Cache[T]) Load

func (c *Cache[T]) Load(fileName string) (T, bool)

Load retrieves an item from the cache if it exists

func (*Cache[T]) LoadLatest

func (c *Cache[T]) LoadLatest(
	filePath string, loader func() (T, error),
) (T, error)

LoadLatest gets the latest version of an item, loading it if stale or missing

func (*Cache[T]) Name added in v1.30.0

func (c *Cache[T]) Name() string

Name returns the cache name for metrics

func (*Cache[T]) Size added in v1.30.0

func (c *Cache[T]) Size() int

Size returns the current number of entries in the cache

func (*Cache[T]) StartEviction

func (c *Cache[T]) StartEviction(ctx context.Context)

StartEviction begins the background process of removing expired items

func (*Cache[T]) Store

func (c *Cache[T]) Store(fileName string, data T, fi os.FileInfo)

Store adds or updates an item in the cache with metadata from the file

type CacheMetrics added in v1.30.0

type CacheMetrics interface {
	// Size returns the current number of entries in the cache
	Size() int
	// Name returns a human-readable name for the cache
	Name() string
}

CacheMetrics provides observability into cache state

type Entry

type Entry[T any] struct {
	Data         T
	Size         int64
	LastModified int64
	ExpiresAt    time.Time
}

Entry represents a single cached item with metadata and expiration information

type FileNotFoundError

type FileNotFoundError struct {
	Path          string
	SearchedPaths []string
}

FileNotFoundError provides detailed information about file search failure

func (*FileNotFoundError) Error

func (e *FileNotFoundError) Error() string

type FileResolver

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

FileResolver handles file path resolution across multiple locations

func NewFileResolver

func NewFileResolver(relativeTos []string) *FileResolver

NewFileResolver creates a new FileResolver instance

func (*FileResolver) ResolveFilePath

func (r *FileResolver) ResolveFilePath(file string) (string, error)

ResolveFilePath attempts to find a file in multiple locations in the following order:

type LogReadOptions

type LogReadOptions struct {
	Head     int    // Number of lines from the beginning
	Tail     int    // Number of lines from the end
	Offset   int    // Line number to start from (1-based)
	Limit    int    // Maximum number of lines to return
	Encoding string // Character encoding for the log file (e.g., "utf-8", "shift_jis", "euc-jp")
}

LogReadOptions defines options for reading log files

type LogResult

type LogResult struct {
	Lines      []string // The lines read from the file
	LineCount  int      // Number of lines returned
	TotalLines int      // Total number of lines in the file
	HasMore    bool     // Whether there are more lines available
	IsEstimate bool     // Whether the TotalLines count is an estimate
}

LogResult represents the result of reading a log file

func ReadLogLines

func ReadLogLines(filePath string, options LogReadOptions) (*LogResult, error)

ReadLogLines reads a specific portion of a log file without loading the entire file into memory

Jump to

Keyboard shortcuts

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