files

package
v1.43.2 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: Apache-2.0 Imports: 16 Imported by: 23

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Copy

func Copy(src string, dst string) error

Copy a file from src to dst

func CopyFromReader

func CopyFromReader(src io.Reader, dst string, mode os.FileMode) (int64, error)

func DoubleStarGlob added in v1.37.0

func DoubleStarGlob(root string, paths []string) ([]string, error)

func Exists

func Exists(path string) bool

Exists returns true if the file exists

func GetBaseName

func GetBaseName(filename string) string

GetBaseName returns the base part of the filename without the extension

func GzipFile

func GzipFile(path string) ([]byte, error)

GzipFile takes the path to a file and returns a Gzip comppressed byte slice

func IsValidPathType added in v1.5.5

func IsValidPathType(input string, extensions ...string) bool

func SafeRead

func SafeRead(path string) string

SafeRead reads a path and returns the text contents or nil

func TempFileName

func TempFileName(prefix, suffix string) string

TempFileName generates a temporary filename for

func UnarchiveExecutables

func UnarchiveExecutables(src, dest string) error

UnarchiveExecutables extracts all executable's to the dest directory, ignoring any path's specified by the archive

func UnarchiveSimple added in v1.42.0

func UnarchiveSimple(src, dest string) error

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 UnfoldGlobs(paths ...string) ([]string, error)

Deprecated: use DoubleStarGlob instead

func Ungzip

func Ungzip(source, target string) error

Ungzip the source file to the target directory

func Untar

func Untar(tarball, target string) error

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 Unxz added in v1.5.11

func Unxz(source, target string) error

func Unzip

func Unzip(src, dest string) error

Unzip the source file to the target directory (backwards compatibility wrapper)

func ValidatePath added in v1.37.0

func ValidatePath(path string) error

ValidatePath validates a single path for security issues

func Zip added in v1.6.2

func Zip(src, dst string) error

Zip the source file/directory into the target destination

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

func UnarchiveWithResult(src, dest string) (*Archive, error)

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

func UntarWithResult(tarball, target string) (*Archive, error)

UntarWithResult extracts all files in tarball to the target directory and returns detailed results

func (*Archive) String added in v1.42.0

func (a *Archive) String() string

String returns a human-readable summary of the archive extraction

type FileFilter

type FileFilter func(header os.FileInfo) string

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

Jump to

Keyboard shortcuts

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