-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
untar.go
83 lines (66 loc) · 1.74 KB
/
untar.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package tar
import (
"archive/tar"
"compress/gzip"
"errors"
"io"
"os"
"path/filepath"
errors2 "github.com/influxdata/influxdb/pkg/errors"
)
// Untar takes a destination path and a reader; a tar reader loops over the tarfile
// creating the file structure at 'dir' along the way, and writing any files
func Untar(dir string, r io.Reader) (rErr error) {
gzr, err := gzip.NewReader(r)
if err != nil {
return err
}
defer errors2.Capture(&rErr, gzr.Close)()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
switch {
// if no more files are found return
case errors.Is(err, io.EOF):
return nil
// return any other error
case err != nil:
return err
// if the header is nil, just skip it (not sure how this happens)
case header == nil:
continue
}
// the target location where the dir/file should be created
target := filepath.Join(dir, header.Name)
// the following switch could also be done using fi.Mode(), not sure if there
// a benefit of using one vs. the other.
// fi := header.FileInfo()
// check the file type
switch header.Typeflag {
// if its a dir and it doesn't exist create it
case tar.TypeDir:
if _, err := os.Stat(target); err != nil {
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
}
// if it's a file create it
case tar.TypeReg:
if err := untarFile(target, tr, header); err != nil {
return err
}
}
}
}
func untarFile(target string, tr *tar.Reader, header *tar.Header) (rErr error) {
f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
if err != nil {
return err
}
defer errors2.Capture(&rErr, f.Close)()
// copy over contents
if _, err := io.Copy(f, tr); err != nil {
return err
}
return nil
}