Documentation
¶
Overview ¶
Package files provides utilities for file operations, archive handling, and path manipulation.
The package offers comprehensive support for working with various archive formats (tar, zip, gzip, xz), file path validation, glob pattern matching, and common file operations.
Key Features:
- Archive extraction with detailed results and statistics
- Support for tar, tar.gz, tar.xz, and zip formats
- Path traversal vulnerability protection
- Glob pattern matching with doublestar support
- File compression and decompression
- Safe file operations with validation
Archive Extraction:
// Simple extraction
err := files.UnarchiveSimple("package.tar.gz", "/dest")
// Extraction with detailed results
result, err := files.Unarchive("package.tar.gz", "/dest")
fmt.Printf("Extracted %d files (%s)\n", len(result.Files), result.String())
// Extraction with options
result, err := files.Unarchive("archive.zip", "/dest",
files.WithOverwrite(true))
// Extract only executables
err := files.UnarchiveExecutables("binaries.tar.gz", "/usr/local/bin")
Compression:
// Gzip a file
data, err := files.GzipFile("document.txt")
// Create a zip archive
err := files.Zip("/source/dir", "archive.zip")
// Decompress xz
err := files.Unxz("file.xz", "file.txt")
// Decompress gzip
err := files.Ungzip("file.gz", "file.txt")
Path Operations:
// Validate path (check for traversal attacks)
err := files.ValidatePath("../../etc/passwd") // Returns error
// Check file type by extension
if files.IsValidPathType("config.yaml", ".yaml", ".yml") {
// Process YAML file
}
// Get base name without extension
name := files.GetBaseName("config.yaml") // "config"
Glob Matching:
// Expand glob patterns
matches, err := files.UnfoldGlobs("**/*.go", "**/*.yaml")
// Match with doublestar patterns
files, err := files.DoubleStarGlob("/project", []string{"**/*.go"})
File Operations:
// Check if file exists
if files.Exists("/path/to/file") {
// File exists
}
// Safe read (returns empty string on error)
content := files.SafeRead("/path/to/file")
// Copy file
err := files.Copy("/source/file", "/dest/file")
// Copy from reader with permissions
n, err := files.CopyFromReader(reader, "/dest/file", 0644)
// Create temp file with custom name
tmpFile := files.TempFileName("prefix-", ".txt")
Archive Results:
The Archive type provides detailed information about extraction operations:
result, _ := files.Unarchive("package.tar.gz", "/dest")
fmt.Printf("Files: %d\n", len(result.Files))
fmt.Printf("Directories: %d\n", len(result.Directories))
fmt.Printf("Symlinks: %d\n", len(result.Symlinks))
fmt.Printf("Size: %s -> %s (%.1f%% compression)\n",
formatSize(result.CompressedSize),
formatSize(result.ExtractedSize),
result.CompressionRatio*100)
Security:
The package includes protection against path traversal vulnerabilities when extracting archives. All paths are validated to ensure they don't escape the destination directory.
Index ¶
- func Copy(src string, dst string) error
- func CopyFromReader(src io.Reader, dst string, mode os.FileMode) (int64, error)
- func DoubleStarGlob(root string, paths []string) ([]string, error)
- func Exists(path string) bool
- func GetBaseName(filename string) string
- func GzipFile(path string) ([]byte, error)
- func IsValidPathType(input string, extensions ...string) bool
- func SafeRead(path string) string
- func TempFileName(prefix, suffix string) string
- func UnarchiveExecutables(src, dest string) error
- func UnarchiveSimple(src, dest string) error
- func UnfoldGlobs(paths ...string) ([]string, error)deprecated
- func Ungzip(source, target string) error
- func Untar(tarball, target string) error
- func UntarWithFilter(tarball, target string, filter FileFilter) error
- func Unxz(source, target string) error
- func Unzip(src, dest string) error
- func ValidatePath(path string) error
- func Zip(src, dst string) error
- type Archive
- func Unarchive(src, dest string, options ...UnarchiveOption) (*Archive, error)
- func UnarchiveWithResult(src, dest string) (*Archive, error)
- func UntarWithFilterAndResult(tarball, target string, filter FileFilter, opts *UnarchiveOptions) (*Archive, error)
- func UntarWithResult(tarball, target string) (*Archive, error)
- type FileFilter
- type UnarchiveOption
- type UnarchiveOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CopyFromReader ¶
func DoubleStarGlob ¶ added in v1.37.0
func GetBaseName ¶
GetBaseName returns the base part of the filename without the extension
func IsValidPathType ¶ added in v1.5.5
func TempFileName ¶
TempFileName generates a temporary filename for
func UnarchiveExecutables ¶
UnarchiveExecutables extracts all executable's to the dest directory, ignoring any path's specified by the archive
func UnarchiveSimple ¶ added in v1.42.0
UnarchiveSimple extracts the contents of an archive to the dest directory (returns only error for backwards compatibility)
func UnfoldGlobs
deprecated
added in
v1.18.0
func Untar ¶
Untar extracts all files in tarball to the target directory (backwards compatibility wrapper)
func UntarWithFilter ¶
func UntarWithFilter(tarball, target string, filter FileFilter) error
UntarWithFilter extracts all files in tarball to the target directory, passing each file to filter if the filter returns "" then the file is ignored, otherwise the return string is used as the relative destination path
func ValidatePath ¶ added in v1.37.0
ValidatePath validates a single path for security issues
Types ¶
type Archive ¶ added in v1.42.0
type Archive struct {
Source string // Path to source archive
Destination string // Extraction destination
Files []string // Successfully extracted files
Directories []string // Created directories
Symlinks []string // Created symlinks
Skipped []string // Skipped entries
Errors []error // Non-fatal errors encountered
Overwritten []string // Files that were overwritten during extraction
// Size metrics
CompressedSize int64 // Size of the archive file
ExtractedSize int64 // Total size of extracted content
CompressionRatio float64 // Ratio of extracted to compressed size
}
Archive represents the result of an archive extraction operation
func Unarchive ¶
func Unarchive(src, dest string, options ...UnarchiveOption) (*Archive, error)
Unarchive extracts an archive and returns detailed results with optional configuration
func UnarchiveWithResult ¶ added in v1.42.0
UnarchiveWithResult is deprecated, use Unarchive instead
func UntarWithFilterAndResult ¶ added in v1.42.0
func UntarWithFilterAndResult(tarball, target string, filter FileFilter, opts *UnarchiveOptions) (*Archive, error)
UntarWithFilterAndResult extracts all files in tarball with filter and returns detailed results
func UntarWithResult ¶ added in v1.42.0
UntarWithResult extracts all files in tarball to the target directory and returns detailed results
type FileFilter ¶
FileFilter is a function used for filtering files
type UnarchiveOption ¶ added in v1.42.0
type UnarchiveOption func(*UnarchiveOptions)
UnarchiveOption is a functional option for configuring archive extraction
func WithOverwrite ¶ added in v1.42.0
func WithOverwrite(overwrite bool) UnarchiveOption
WithOverwrite sets whether existing files should be overwritten during extraction
type UnarchiveOptions ¶ added in v1.42.0
type UnarchiveOptions struct {
Overwrite bool // Allow overwriting existing files
}
UnarchiveOptions configures archive extraction behavior