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 ¶
- func Unzip(srcFile, dstPath string) error
- func UnzipFromBytes(data []byte, dstPath string, filter FilterFunc) error
- func UnzipFromFile(srcFile, dstPath string, filter FilterFunc) error
- func Zip(srcPath, dstPath string) error
- func ZipAppend(srcZipBytes []byte, pathToAppend string, zippedContent []byte) ([]byte, error)
- func ZipMapToBytes(fileMap FileMap) ([]byte, error)
- func ZipToBytes(srcPath string, filter FilterFunc) ([]byte, error)
- func ZipToFile(srcPath, dstPath string, filter FilterFunc) error
- type FileMap
- func (fm FileMap) Delete(filePath string)
- func (fm FileMap) ExportToDir(destDir string) error
- func (fm FileMap) Get(filePath string) ([]byte, bool)
- func (fm FileMap) Has(filePath string) bool
- func (fm FileMap) Paths() []string
- func (fm FileMap) Set(filePath string, data []byte)
- func (fm FileMap) Validate() error
- type FilterFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Unzip ¶
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 ¶
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 ¶
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
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
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
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
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) ExportToDir ¶ added in v0.4.0
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
Get returns the contents of the file at the given path and a boolean indicating whether the file exists in the map.
type FilterFunc ¶
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.
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.