-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
tar.go
51 lines (46 loc) · 971 Bytes
/
tar.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
package testutil
import (
"archive/tar"
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"github.com/pkg/errors"
)
type TarItem struct {
Header *tar.Header
Data []byte
}
func ReadTarToMap(dt []byte, compressed bool) (map[string]*TarItem, error) {
m := map[string]*TarItem{}
var r io.Reader = bytes.NewBuffer(dt)
if compressed {
gz, err := gzip.NewReader(r)
if err != nil {
return nil, errors.Wrapf(err, "error creating gzip reader")
}
defer gz.Close()
r = gz
}
tr := tar.NewReader(r)
for {
h, err := tr.Next()
if err != nil {
if err == io.EOF {
return m, nil
}
return nil, errors.Wrap(err, "error reading tar")
}
if _, ok := m[h.Name]; ok {
return nil, errors.Errorf("duplicate entries for %s", h.Name)
}
var dt []byte
if h.Typeflag == tar.TypeReg {
dt, err = ioutil.ReadAll(tr)
if err != nil {
return nil, errors.Wrapf(err, "error reading file")
}
}
m[h.Name] = &TarItem{Header: h, Data: dt}
}
}