forked from zyedidia/eget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZipArchive.go
62 lines (52 loc) · 1.06 KB
/
ZipArchive.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package archives
import (
"archive/zip"
"bytes"
"fmt"
"io"
"strings"
"github.com/permafrost-dev/eget/lib/files"
)
type ZipArchive struct {
r *zip.Reader
idx int
}
// decompressor does nothing for a zip archive because it already has built-in
// compression.
func NewZipArchive(data []byte, _ DecompressFunc) (Archive, error) {
r := bytes.NewReader(data)
zr, err := zip.NewReader(r, int64(len(data)))
return &ZipArchive{
r: zr,
idx: -1,
}, err
}
func (z *ZipArchive) Next() (files.File, error) {
z.idx++
if z.idx < 0 || z.idx >= len(z.r.File) {
return files.File{}, io.EOF
}
f := z.r.File[z.idx]
typ := files.TypeNormal
if strings.HasSuffix(f.Name, "/") {
typ = files.TypeDir
}
return files.File{
Name: f.Name,
Mode: f.Mode(),
Type: typ,
}, nil
}
func (z *ZipArchive) ReadAll() ([]byte, error) {
if z.idx < 0 || z.idx >= len(z.r.File) {
return nil, io.EOF
}
f := z.r.File[z.idx]
rc, err := f.Open()
if err != nil {
return nil, fmt.Errorf("zip extract: %w", err)
}
defer rc.Close()
data, err := io.ReadAll(rc)
return data, err
}