gozu

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 9 Imported by: 0

README

gozu

Go Reference

gozu - Go Zip Utilities

A comprehensive Go library for creating and extracting zip archives with support for filtering, in-memory operations, and archive manipulation.

Features

  • Basic Operations: Zip directories and unzip archives with a single function call
  • Filtered Operations: Selectively include/exclude files during compression and extraction
  • In-Memory Operations: Work with zip archives entirely in memory without filesystem access
  • FileMap Type: Pure in-memory file manipulation using map[string][]byte
  • Archive Appending: Merge content into existing zip archives
  • Cross-Platform: Uses forward slashes for consistent path handling
  • Security: Built-in protection against zip slip attacks

Installation

go get github.com/miroslav-matejovsky/gozu

Usage

Basic Operations
import "github.com/miroslav-matejovsky/gozu"

// Zip a directory
err := gozu.Zip("path/to/dir", "output.zip")

// Unzip a zip file
err = gozu.Unzip("input.zip", "path/to/extract")
Filtered Operations

Use filters to selectively include files:

// Zip only .txt files
filter := func(path string, info fs.FileInfo) bool {
    return filepath.Ext(path) == ".txt"
}
err := gozu.ZipToFile("path/to/dir", "output.zip", filter)

// Unzip only files smaller than 1MB
sizeFilter := func(path string, info fs.FileInfo) bool {
    return info.Size() < 1024*1024
}
err := gozu.UnzipFromFile("archive.zip", "output", sizeFilter)
In-Memory Operations

Work with zip archives as byte slices:

// Compress directory to bytes
data, err := gozu.ZipToBytes("path/to/dir", gozu.AllowAll)

// Extract bytes to directory
err = gozu.UnzipFromBytes(data, "path/to/extract", gozu.AllowAll)
FileMap Operations

For pure in-memory operations without filesystem access:

// Create a FileMap with file contents
files := gozu.FileMap{
    "readme.txt":      []byte("Hello, World!"),
    "src/main.go":     []byte("package main"),
    "data/config.json": []byte(`{"key": "value"}`),
}

// Zip the FileMap to bytes
zipData, err := gozu.ZipMapToBytes(files)

// Unzip bytes back to a FileMap
extracted, err := gozu.UnzipBytesToMap(zipData)

// FileMap helper methods
files.Set("new.txt", []byte("new content"))
content, ok := files.Get("readme.txt")
files.Delete("old.txt")
exists := files.Has("readme.txt")
paths := files.Paths()
Archive Appending

Add content to existing zip archives:

// Append new zip content under a specific path
updated, err := gozu.ZipAppend(existingZip, "subdir", newContent)

Filters

Predefined Filters
  • AllowAll: Includes all files (default behavior)
Combining Filters
combined := gozu.CombineFilters(filter1, filter2, filter3)
Constructing Filters

NewFilterFunc accepts either a full FilterFunc, a path-only predicate, or an info-only predicate:

// Path-only filter
pathOnly := gozu.NewFilterFunc(func(path string) bool {
    return strings.HasPrefix(path, "docs/")
})

// FileInfo-only filter
infoOnly := gozu.NewFilterFunc(func(info fs.FileInfo) bool {
    return info.Size() > 0
})

API Reference

Types
Type Description
FileMap map[string][]byte for in-memory file representation
FilterFunc func(path string, info fs.FileInfo) bool for filtering
Functions
Function Description
Zip(src, dst) Zip a directory to a file
Unzip(src, dst) Unzip a file to a directory
ZipToFile(src, dst, filter) Zip with filtering
ZipToBytes(src, filter) Zip to in-memory bytes
UnzipFromFile(src, dst, filter) Unzip with filtering
UnzipFromBytes(data, dst, filter) Unzip from in-memory bytes
ZipMapToBytes(files) Zip a FileMap to bytes
UnzipBytesToMap(data) Unzip bytes to a FileMap
ZipAppend(src, path, content) Append content to a zip archive

License

See LICENSE for details.

Documentation

Overview

Package gozu provides utilities for creating and extracting zip archives in Go.

gozu offers a comprehensive set of functions for working with zip files, supporting both filesystem-based and in-memory operations with flexible filtering capabilities.

Features

  • Create zip archives from directories
  • Extract zip archives to directories
  • In-memory zip operations (no filesystem required)
  • Flexible file filtering during compression and extraction
  • Append content to existing zip archives
  • FileMap type for pure in-memory file manipulation
  • Cross-platform path handling (uses forward slashes)
  • Protection against zip slip attacks

Basic Operations

The simplest way to create and extract zip archives:

// Zip a directory
err := gozu.Zip("path/to/dir", "output.zip")

// Unzip to a directory
err := gozu.Unzip("input.zip", "path/to/extract")

Filtered Operations

Use FilterFunc to selectively include or exclude files:

// Zip only .go files
filter := func(path string, info fs.FileInfo) bool {
    return strings.HasSuffix(path, ".go")
}
err := gozu.ZipToFile("src", "source.zip", filter)

// Extract only files smaller than 1MB
sizeFilter := func(path string, info fs.FileInfo) bool {
    return info.Size() < 1024*1024
}
err := gozu.UnzipFromFile("archive.zip", "output", sizeFilter)

Use NewFilterFunc to create filters from simpler predicates:

// Path-only filter
pathFilter := gozu.NewFilterFunc(func(path string) bool {
    return strings.HasPrefix(path, "docs/")
})

// FileInfo-only filter
infoFilter := gozu.NewFilterFunc(func(info fs.FileInfo) bool {
    return !info.IsDir()
})

Combine multiple filters with CombineFilters:

combined := gozu.CombineFilters(filter1, filter2, filter3)

In-Memory Operations

Work with zip archives entirely in memory:

// Compress directory to bytes
data, err := gozu.ZipToBytes("path/to/dir", gozu.AllowAll)

// Extract bytes to directory
err := gozu.UnzipFromBytes(data, "path/to/extract", gozu.AllowAll)

FileMap Operations

For pure in-memory operations without filesystem access, use FileMap:

// Create a FileMap with file contents
files := gozu.FileMap{
    "readme.txt":     []byte("Hello, World!"),
    "src/main.go":    []byte("package main"),
    "data/config.json": []byte(`{"key": "value"}`),
}

// Zip the FileMap to bytes
zipData, err := gozu.ZipMapToBytes(files)

// Unzip bytes back to a FileMap
extracted, err := gozu.UnzipBytesToMap(zipData)

FileMap provides helper methods for manipulation:

files.Set("new.txt", []byte("new content"))
content, ok := files.Get("readme.txt")
files.Delete("old.txt")
exists := files.Has("readme.txt")
paths := files.Paths()

Appending to Archives

Add content to existing zip archives:

// Append new zip content under a specific path
updated, err := gozu.ZipAppend(existingZip, "subdir", newContent)

Error Handling

All functions return wrapped errors with context using fmt.Errorf and %w, making it easy to understand the cause of failures and use errors.Is/errors.As.

Thread Safety

The functions in this package are not safe for concurrent use on the same files or data. Callers should synchronize access when needed.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Unzip

func Unzip(srcFile, dstPath string) error

Unzip extracts all files from the zip archive at srcFile to the directory at dstPath. Creates the destination directory if it doesn't exist. Returns an error if the archive cannot be read or files cannot be extracted.

func UnzipFromBytes

func UnzipFromBytes(data []byte, dstPath string, filter FilterFunc) error

UnzipFromBytes extracts files from an in-memory zip archive to the directory at dstPath. The filter function is called for each file to determine if it should be extracted. Use AllowAll to extract all files, or provide a custom FilterFunc for selective extraction. Returns an error if the archive is invalid or files cannot be extracted.

func UnzipFromFile

func UnzipFromFile(srcFile, dstPath string, filter FilterFunc) error

UnzipFromFile extracts files from the zip archive at srcFile to the directory at dstPath. The filter function is called for each file to determine if it should be extracted. Use AllowAll to extract all files, or provide a custom FilterFunc for selective extraction. Returns an error if the archive cannot be read or files cannot be extracted.

func Zip

func Zip(srcPath, dstPath string) error

Zip compresses the directory at srcPath into a zip archive at dstPath. All files and subdirectories are included recursively. Returns an error if the source directory cannot be read or the destination file cannot be created.

func ZipAppend

func ZipAppend(srcZipBytes []byte, pathToAppend string, zippedContent []byte) ([]byte, error)

ZipAppend merges zippedContent into the existing zip archive provided by srcZipBytes. The appended files are placed under the specified path inside the archive (use an empty path to append at the root). If srcZipBytes is empty, the function creates a new archive containing only the appended content. Returns the updated archive as a byte slice.

func ZipMapToBytes added in v0.4.0

func ZipMapToBytes(fileMap FileMap) ([]byte, error)

ZipMapToBytes creates an in-memory zip archive from the provided map of file paths to their byte contents. File paths in the map should use forward slashes (e.g., "dir/file.txt"). Returns the zip archive as a byte slice or an error if the operation fails.

func ZipToBytes

func ZipToBytes(srcPath string, filter FilterFunc) ([]byte, error)

ZipToBytes compresses the directory at srcPath into an in-memory zip archive. The filter function is called for each file to determine if it should be included. Use AllowAll to include all files, or provide a custom FilterFunc for selective archiving. Returns the zip archive as a byte slice, or an error if compression fails.

func ZipToFile

func ZipToFile(srcPath, dstPath string, filter FilterFunc) error

ZipToFile compresses the directory at srcPath into a zip archive at dstPath. The filter function is called for each file to determine if it should be included. Use AllowAll to include all files, or provide a custom FilterFunc for selective archiving. Returns an error if the source directory cannot be read or the destination file cannot be created.

Types

type FileMap added in v0.4.0

type FileMap map[string][]byte

FileMap represents a mapping of file paths to their byte contents. Keys are forward-slash separated paths (e.g., "dir/file.txt"). This type is useful for in-memory zip operations without filesystem access.

func FileMapFromDir added in v0.4.0

func FileMapFromDir(srcDir string) (FileMap, error)

FileMapFromDir builds a FileMap from all files found under srcDir. Paths in the resulting map use forward slashes and are relative to srcDir.

func UnzipBytesToMap added in v0.4.0

func UnzipBytesToMap(data []byte) (FileMap, error)

UnzipBytesToMap extracts files from an in-memory zip archive represented by the provided byte slice. Returns a FileMap containing file paths mapped to their byte contents. Directories are not included in the returned map. Returns an error if the archive is invalid or files cannot be read.

func (FileMap) Delete added in v0.4.0

func (fm FileMap) Delete(filePath string)

Delete removes a file from the map.

func (FileMap) ExportToDir added in v0.4.0

func (fm FileMap) ExportToDir(destDir string) error

ExportToDir writes the FileMap contents to destDir, creating directories as needed. Existing files with the same paths are overwritten.

func (FileMap) Get added in v0.4.0

func (fm FileMap) Get(filePath string) ([]byte, bool)

Get returns the contents of the file at the given path and a boolean indicating whether the file exists in the map.

func (FileMap) Has added in v0.4.0

func (fm FileMap) Has(filePath string) bool

Has returns true if the file exists in the map.

func (FileMap) Paths added in v0.4.0

func (fm FileMap) Paths() []string

Paths returns all file paths in the map.

func (FileMap) Set added in v0.4.0

func (fm FileMap) Set(filePath string, data []byte)

Set adds or updates a file in the map with the given path and contents.

func (FileMap) Validate added in v0.4.0

func (fm FileMap) Validate() error

Validate ensures the FileMap only contains safe, relative paths and non-nil data. Paths must not be empty, reference the current directory, be absolute, or include up-level segments.

type FilterFunc

type FilterFunc func(path string, info fs.FileInfo) bool

FilterFunc is a function type used to filter files during zip operations. It takes a file path (relative to the zip root) and file info, returning true to include the file or false to exclude it. This allows selective inclusion of files based on custom criteria like path patterns, file types, or directory depth.

Example usage:

  • To include only .txt files: func(path string, info fs.FileInfo) bool { return filepath.Ext(path) == ".txt" }
  • To exclude hidden files: func(path string, info fs.FileInfo) bool { return !strings.HasPrefix(filepath.Base(path), ".") }
  • Combine with predefined filters for common cases.
var AllowAll FilterFunc = func(path string, info fs.FileInfo) bool {
	return true
}

AllowAll is a predefined FilterFunc that allows all files. It can be used as a default filter when no filtering is needed.

func CombineFilters

func CombineFilters(filters ...FilterFunc) FilterFunc

CombineFilters combines multiple FilterFunc functions into a single FilterFunc. The combined filter returns true only if all individual filters return true for a given file. This allows for flexible and reusable filtering logic by composing simple filters.

func NewFilterFunc added in v0.4.0

func NewFilterFunc[Fn filterConstructor](fn Fn) FilterFunc

NewFilterFunc builds a FilterFunc from a path-only, info-only, or full predicate. This generic constructor allows creating FilterFunc instances from simpler function types, making it easier to define filters without always needing to handle both path and info.

Parameters:

  • fn: A function that matches one of the supported signatures.

Returns:

  • A FilterFunc that adapts the input function to the full signature.

Examples:

  • Path-only: NewFilterFunc(func(path string) bool { return strings.HasSuffix(path, ".go") })
  • Info-only: NewFilterFunc(func(info fs.FileInfo) bool { return info.Size() > 0 })
  • Full: NewFilterFunc(func(path string, info fs.FileInfo) bool { return true })

The function uses type switching to determine the input function's signature and wraps it accordingly. For path-only functions, the info parameter is ignored. For info-only functions, the path parameter is ignored. For full functions, it's returned as-is.

Jump to

Keyboard shortcuts

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