zipx

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2022 License: MIT Imports: 11 Imported by: 1

README

zip extractor

PkgGoDev Actions/Go Go Report Card

Package to make zip extraction easy (less codes) and efficient.

$ go get github.com/koron-go/zipx
import (
    "github.com/koron-go/zipx"
    "context"
)

func main() {
    err := zipx.New().ExtractFile(context.Background(), "archive.zip", zipx.Dir("outdir"))
    if err != nil {
        panic(err)
    }
}

See GoDoc for references.

Features

  • Concurrent extraction

    • Auto concurrency. Use runtime.NumCPU() as default.

    • Configurable by manual

      // no concurrency (=sequential)
      x1 := zipx.New().WithConcurrency(1)
      
      // full concurrency, no limits. it would be slow.
      x0 := zipx.New().WithConcurrency(0)
      
  • Customizable progress monitor

    var lastPercent = -1
    
    func monitor(p zipx.Progress) {
        curr := (p.NumDone * 10 / p.NumTotal) * 10
        if curr > lastPercent {
            lastPercent = curr
            report.Printf("progress %d%%", curr)
        }
    }
    
    func main() {
        err := zipx.New().
            WithMonitor(zipx.MonitorFunc(monitor)).
            ExtractFile(context.Background(), "archive.zip", zipx.Dir("outdir"))
        // ...(snip)...
    }
    
  • Configurable zipx.Destination

    • Where to extract files are configurable by implementing zipx.Destination interface.

    • zipx provides two zipx.Destination implementaions.

      • for files: zipx.Dir
      • black hole: zipx.Discard
    • Using zipx.Dir, you can support names with other encodings rather than "UTF-8" easily by configuring zip.DefaultReinterpreter.

      // Example to support ShiftJIS (Windows or so)
      import "golang.org/x/text/encoding/japanese"
      
      func shiftjis(s string) (string, error) {
          d := japanese.ShiftJIS.NewDecoder()
          return d.String(s)
      }
      
      zipx.DefaultReinterpreter = ReinterpretFunc(shiftjis)
      
      // ...(snip)...
      
      err := zipx.New().ExtractFile(context.Background(), "archive.zip",
          zipx.Dir("outdir"))
      // ...(snip)...
      
  • Cancelable by context.Context

    // Example to cancel extraction after 5 seconds.
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    go func() {
        time.Sleep(5 * time.Second)
        cancel()
    }()
    
    err := zipx.New().ExtractFile(ctx, "archive.zip", zipx.Dir("outdir"))
    if err != nil {
        // this would be "context canceled", if the extraction took over 5
        // seconds.
        log.Print(err)
    }
    

Why use zipx ?

golang では archive/zip 使えば容易にZIPの解凍は実装できます。しかしファイル 作ったり並列にして速度だしたりプログレスだしたりといったよくある実装は、自分で やらなきゃいけなくてちょっと面倒でした。

zipx ではZIPの解凍で頻繁に必要になるそれらの手続きをパッケージングしました。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultReinterpreter = ReinterpretFunc(noReinterpret)

DefaultReinterpreter is used by Dir (Destination)

View Source
var NullMonitor = MonitorFunc(func(_ Progress) {

})

NullMonitor is monitor which ignores progress entirely.

Functions

This section is empty.

Types

type Destination

type Destination interface {
	// CreateDir creates a new directory in destination.
	CreateDir(name string, info DirInfo) error

	// CreateFile creates a new file in destination.
	//
	// This can return io.WriteCloser as 1st return parameter, in that case
	// zipx close it automatically after have finished to use.
	CreateFile(name string, info FileInfo) (io.Writer, error)
}

Destination provides destination for extraction.

var Discard Destination = &discard{}

Discard is a destination which discard all extracted files and dirs.

func Dir

func Dir(name string) Destination

Dir creates simple directory Destination.

type DirInfo

type DirInfo struct {
	// NonUTF8 indicates name would be non UTF-8 encoding.
	NonUTF8 bool

	// Mode represents directory's mode and permission bits.
	Mode os.FileMode
}

DirInfo describes meta information of a dir.

type FileInfo

type FileInfo struct {
	// NonUTF8 indicates name would be non UTF-8 encoding.
	NonUTF8 bool

	// Size is estimated size to write.
	Size uint64

	// Modified is last updated time of file.
	Modified time.Time

	// Mode represents file's mode and permission bits.
	Mode os.FileMode
}

FileInfo describes meta information of a file.

type Monitor

type Monitor interface {
	Monitor(Progress)
}

Monitor monitors progress of extraction.

type MonitorFunc

type MonitorFunc func(Progress)

MonitorFunc is used to implement Monitor by function.

func (MonitorFunc) Monitor

func (f MonitorFunc) Monitor(p Progress)

Monitor monitors progress of extraction.

type Progress

type Progress struct {
	// NumDone is number of extracted files.
	NumDone int

	// NumTotal is number of total files.
	NumTotal int
}

Progress holds progress of extraction.

type ReinterpretFunc

type ReinterpretFunc func(string) (string, error)

ReinterpretFunc is used to implement Reinterpreter with function.

func (ReinterpretFunc) Reinterpret

func (f ReinterpretFunc) Reinterpret(s string) (string, error)

Reinterpret re-interprets string with another encoding.

type Reinterpreter

type Reinterpreter interface {
	Reinterpret(string) (string, error)
}

Reinterpreter provides correction of encoding of names for files and dirs.

type ZipX

type ZipX struct {
	// contains filtered or unexported fields
}

ZipX is a zip archive extractor.

func New

func New() *ZipX

New creates a extractor for zip archive.

func (*ZipX) Concurrency

func (x *ZipX) Concurrency() int

Concurrency get current concurrency of extraction.

func (*ZipX) Extract

func (x *ZipX) Extract(ctx context.Context, r *zip.Reader, d Destination) error

Extract extracts all files from *zip.Reader as a zip archive.

func (*ZipX) ExtractFile

func (x *ZipX) ExtractFile(ctx context.Context, name string, d Destination) error

ExtractFile extracts all files from a zip archive file "name".

func (*ZipX) SetConcurrency

func (x *ZipX) SetConcurrency(n int)

SetConcurrency updates concurrency of extraction. 0 means no limitation.

func (*ZipX) SetMonitor

func (x *ZipX) SetMonitor(m Monitor)

SetMonitor updates a monitor of progress.

func (*ZipX) WithConcurrency

func (x *ZipX) WithConcurrency(n int) *ZipX

WithConcurrency updates practical of extraction. 0 means no limitation.

func (*ZipX) WithMonitor

func (x *ZipX) WithMonitor(m Monitor) *ZipX

WithMonitor updates a monitor of progress.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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