fileutils

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2025 License: MIT Imports: 18 Imported by: 3

README

fileutils Build Status Go Report Card Coverage Status

Package fileutils provides useful, high-level file operations.

Details

  • IsFile & IsDir checks if file/directory exists
  • CopyFile copies a file from source to destination, preserving mode
  • CopyDir copies all files recursively from the source to destination directory
  • MoveFile moves a file, using atomic rename when possible with copy+delete fallback
  • ListFiles returns sorted slice of file paths in directory
  • TempFileName returns a new temporary file name using secure random generation
  • SanitizePath cleans file path
  • TouchFile creates an empty file or updates timestamps of existing one
  • Checksum calculates file checksum using various hash algorithms (MD5, SHA1, SHA256, etc.)
  • FileWatcher watches files or directories for changes
  • WatchRecursive watches a directory recursively for changes

Usage Examples

File Operations
// Copy a file
err := fileutils.CopyFile("source.txt", "destination.txt")
if err != nil {
    log.Fatalf("Failed to copy file: %v", err)
}

// Move a file
err = fileutils.MoveFile("source.txt", "destination.txt")
if err != nil {
    log.Fatalf("Failed to move file: %v", err)
}

// Check if a file or directory exists
if fileutils.IsFile("file.txt") {
    fmt.Println("File exists")
}
if fileutils.IsDir("directory") {
    fmt.Println("Directory exists")
}

// Generate a temporary file name
tempName, err := fileutils.TempFileName("/tmp", "prefix-*.ext")
if err != nil {
    log.Fatalf("Failed to generate temp file name: %v", err)
}
fmt.Println("Temp file:", tempName)
File Checksum
// Calculate MD5 checksum
md5sum, err := fileutils.Checksum("path/to/file", enum.HashAlgMD5)
if err != nil {
    log.Fatalf("Failed to calculate MD5: %v", err)
}
fmt.Printf("MD5: %s\n", md5sum)

// Calculate SHA256 checksum
sha256sum, err := fileutils.Checksum("path/to/file", enum.HashAlgSHA256)
if err != nil {
    log.Fatalf("Failed to calculate SHA256: %v", err)
}
fmt.Printf("SHA256: %s\n", sha256sum)
File Watcher
// Create a simple file watcher
watcher, err := fileutils.NewFileWatcher("/path/to/file", func(event FileEvent) {
    fmt.Printf("Event: %s, Path: %s\n", event.Type, event.Path)
})
if err != nil {
    log.Fatalf("Failed to create watcher: %v", err)
}
defer watcher.Close()

// Watch a directory recursively
watcher, err := fileutils.WatchRecursive("/path/to/dir", func(event FileEvent) {
    fmt.Printf("Event: %s, Path: %s\n", event.Type, event.Path)
})
if err != nil {
    log.Fatalf("Failed to create watcher: %v", err)
}
defer watcher.Close()

// Add another path to an existing watcher
err = watcher.AddPath("/path/to/another/file")

// Remove a path from the watcher
err = watcher.RemovePath("/path/to/file")

Install and update

go get -u github.com/go-pkgz/fileutils

Documentation

Overview

Package fileutils provides useful, high-level file operations

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Checksum added in v0.4.0

func Checksum(path string, algo enum.HashAlg) (string, error)

Checksum calculates the checksum of a file using the specified hash algorithm. Supported algorithms are MD5, SHA1, SHA224, SHA256, SHA384, SHA512, SHA512_224, and SHA512_256.

func CopyDir

func CopyDir(src, dst string) error

CopyDir copies all files from src to dst, recursively

func CopyFile

func CopyFile(src, dst string) error

CopyFile copies a file from source to dest, preserving mode. Any existing file will be overwritten.

func IsDir

func IsDir(dirname string) bool

IsDir returns true if directory exists

func IsFile

func IsFile(filename string) bool

IsFile returns true if filename exists

func ListFiles

func ListFiles(directory string) (list []string, err error)

ListFiles gets recursive list of all files in a directory

func MoveFile added in v0.3.0

func MoveFile(src, dst string) error

MoveFile moves a file from src to dst. If rename fails (e.g., cross-device move), it will fall back to copy+delete. It will create destination directories if they don't exist.

func SanitizePath added in v0.2.0

func SanitizePath(s string) string

SanitizePath returns a sanitized version of the given path.

func TempFileName added in v0.2.0

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

TempFileName returns a new temporary file name in the directory dir. 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 "*". If dir is the empty string, TempFileName uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempFileName simultaneously will not choose the same file name.

func TouchFile added in v0.3.0

func TouchFile(path string) error

TouchFile creates an empty file if it doesn't exist, or updates access and modification times if it does.

Types

type FileEvent added in v0.4.0

type FileEvent struct {
	Path string         // path to the file or directory
	Type enum.EventType // type of event
}

FileEvent represents a file system event

type FileWatcher added in v0.4.0

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

FileWatcher watches for file system events

func NewFileWatcher added in v0.4.0

func NewFileWatcher(path string, callback func(FileEvent)) (*FileWatcher, error)

NewFileWatcher creates a new file watcher for the specified path

func WatchRecursive added in v0.4.0

func WatchRecursive(dir string, callback func(FileEvent)) (*FileWatcher, error)

WatchRecursive watches a directory recursively

func (*FileWatcher) AddPath added in v0.4.0

func (fw *FileWatcher) AddPath(path string) error

AddPath adds a path to the watcher

func (*FileWatcher) Close added in v0.4.0

func (fw *FileWatcher) Close() error

Close stops watching and releases resources

func (*FileWatcher) RemovePath added in v0.4.0

func (fw *FileWatcher) RemovePath(path string) error

RemovePath removes a path from the watcher

Directories

Path Synopsis
Code generated by enum generator; DO NOT EDIT.
Code generated by enum generator; DO NOT EDIT.

Jump to

Keyboard shortcuts

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