archive

package
v0.1.102 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2026 License: BSD-3-Clause Imports: 14 Imported by: 0

README

Unified Archive Library

This package is a high-level, cross-platform archive abstraction library. It wraps unxed/zip and unxed/tar to leverage high-performance and high-fidelity features (such as parallel writing/extracting, NTFS ACLs, UNIX xattrs, and seekable solid archives) while gracefully falling back to standard Go implementations for other formats (via mholt/archives).

Core API Interfaces

1. Options

Configuration struct for both archiving and extraction operations.

type Options struct {
	Concurrency    int
	Xattrs         bool
	Solid          bool
	Method         string // "zstd", "deflate", "gzip", "store", "lzma", "bzip2", "xz"
	Password       string
	EncryptCD      bool
	SeekChunkSize  uint32
	SeekContinuous bool
	Incremental    bool
	IndexPath      string
	EmbeddedIdx    bool

	// Extractor specific
	KeepOldFiles   bool
	KeepNewerFiles bool
	KeepBroken     bool
	Sparse         bool
	Tolerant       bool
	SafeWrites     bool
	UnlinkFirst    bool
	NumericOwner   bool
}
2. Archiver & Extractor

Used for batch file packing and unpacking.

type Archiver interface {
	Archive(ctx context.Context, files map[string]os.FileInfo) error
	Close() error
}

type Extractor interface {
	Extract(ctx context.Context) error
	Close() error
}
3. FileSystem

Provides read-only VFS access (fs.FS) to zip, tar, and fallback formats.

type FileSystem interface {
	fs.FS
	fs.ReadDirFS
	fs.StatFS
	io.Closer
}
4. Updater

Enables in-place modifications (append/remove) on supported formats.

type Updater interface {
	Append(name string, size int64, r io.Reader) error
	Remove(name string) error
	Close() error
}

Code Examples

1. File Extraction
package main

import (
	"context"
	"log"
	"github.com/unxed/zipper/archive"
)

func main() {
	opts := archive.Options{Xattrs: true, SafeWrites: true}
	e, err := archive.NewExtractor("my_archive.zip", "./output_dir", opts)
	if err != nil {
		log.Fatal(err)
	}
	defer e.Close()

	if err := e.Extract(context.Background()); err != nil {
		log.Fatal(err)
	}
}
2. Reading files via fs.FS (Virtual File System)
package main

import (
	"fmt"
	"io"
	"log"
	"github.com/unxed/zipper/archive"
)

func main() {
	fsys, err := archive.OpenFS("archive.tar.zst", archive.Options{})
	if err != nil {
		log.Fatal(err)
	}
	defer fsys.Close()

	f, err := fsys.Open("nested/file.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	data, _ := io.ReadAll(f)
	fmt.Println(string(data))
}
3. In-place Append
package main

import (
	"log"
	"strings"
	"github.com/unxed/zipper/archive"
)

func main() {
	upd, err := archive.NewUpdater("existing.zip", archive.Options{})
	if err != nil {
		log.Fatal(err)
	}
	defer upd.Close()

	content := "updated data stream"
	r := strings.NewReader(content)

	err = upd.Append("config.txt", int64(len(content)), r)
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultFormat

func DefaultFormat() string

DefaultFormat возвращает предпочтительный формат архива для текущей ОС.

func DetectFormat

func DetectFormat(filename string) string

DetectFormat определяет тип движка (zip, tar или fallback) на основе имени файла.

func GenerateExternalPar2 added in v0.1.13

func GenerateExternalPar2(filename string, pct int) error

GenerateExternalPar2 генерирует внешний файл .par2 рядом с архивом.

func RepairTarArchive added in v0.1.10

func RepairTarArchive(filename string) error

RepairTarArchive извлекает .tarext/par2/recovery.par2 из TAR-архива (Stream 2) и чинит архив in-place (в том числе многотомный) через unxed/par2.

func RepairZipArchive added in v0.1.10

func RepairZipArchive(filename string) error

RepairZipArchive извлекает скрытый по стандарту SOZip файл .recovery.par2 и чинит архив in-place (в том числе многотомный) через unxed/par2.

func SpoolStdin added in v0.1.24

func SpoolStdin() (string, error)

Types

type Archiver

type Archiver interface {
	Archive(ctx context.Context, files map[string]os.FileInfo) error
	Close() error
	Progresser
}

Archiver описывает абстрактный интерфейс для создания архивов.

func NewArchiver

func NewArchiver(filename, chroot string, opts Options) (Archiver, error)

NewArchiver возвращает соответствующий Archiver на основе имени файла.

func NewFallbackArchiver

func NewFallbackArchiver(filename, chroot string, opts Options) (Archiver, error)

func NewTarArchiver

func NewTarArchiver(filename, chroot string, opts Options) (Archiver, error)

func NewZipArchiver

func NewZipArchiver(filename, chroot string, opts Options) (Archiver, error)

type Extractor

type Extractor interface {
	Extract(ctx context.Context) error
	Close() error
	Progresser
}

Extractor описывает абстрактный интерфейс для распаковки архивов.

func NewExtractor

func NewExtractor(filename, chroot string, opts Options) (Extractor, error)

NewExtractor возвращает соответствующий Extractor на основе имени файла.

func NewFallbackExtractor

func NewFallbackExtractor(filename, chroot string, opts Options) (Extractor, error)

func NewTarExtractor

func NewTarExtractor(filename, chroot string, opts Options) (Extractor, error)

func NewZipExtractor

func NewZipExtractor(filename, chroot string, opts Options) (Extractor, error)

type FileSystem

type FileSystem interface {
	fs.FS
	fs.ReadDirFS
	fs.StatFS
	io.Closer
}

func OpenFS

func OpenFS(filename string, opts Options) (FileSystem, error)

type Options

type Options struct {
	Concurrency int
	Xattrs      bool
	Solid       bool
	Method      string // "zstd", "deflate", "gzip", "store", "lzma", "bzip2", "xz"
	Level       int    // Compression level (1-9)

	Password       string
	EncryptCD      bool
	SeekChunkSize  uint32
	SeekContinuous bool
	SplitSize      int64

	// Archiver specific
	Incremental bool
	IndexPath   string
	EmbeddedIdx bool
	NonSolid    bool

	// Extractor specific
	RecoveryPct int

	KeepOldFiles   bool
	KeepNewerFiles bool
	KeepBroken     bool
	Sparse         bool
	Tolerant       bool
	SafeWrites     bool
	UnlinkFirst    bool
	NumericOwner   bool

	TorrentZip         bool
	NoPlatformMetadata bool
	NoTimes            bool
	StripComponents    int
	MaxFileSize        int64
	MaxRatio           int64
	RecoveryExternal   bool
	Lock               bool
	PathMapping        map[string]string
}

Options содержит унифицированные параметры как для zip, так и для tar.

type Progresser added in v0.1.23

type Progresser interface {
	Written() (bytes, entries int64)
}

Progresser описывает интерфейс для получения статистики процесса

type Updater

type Updater interface {
	Append(name string, size int64, r io.Reader) error
	Remove(name string) error
	Close() error
}

func NewUpdater

func NewUpdater(filename string, opts Options) (Updater, error)

type VolumeReaderRW added in v0.1.10

type VolumeReaderRW interface {
	ReadAt(p []byte, off int64) (n int, err error)
	WriteAt(p []byte, off int64) (n int, err error)
}

Jump to

Keyboard shortcuts

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