-
Notifications
You must be signed in to change notification settings - Fork 90
/
tar.go
67 lines (54 loc) · 1.24 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package util
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
)
func ExtractTGZArchive(tgzFile string, destDir string) error {
fileReader, err := os.Open(tgzFile)
if err != nil {
return errors.Wrap(err, "failed to open tgz file")
}
gzReader, err := gzip.NewReader(fileReader)
if err != nil {
return errors.Wrap(err, "failed to create gzip reader")
}
tarReader := tar.NewReader(gzReader)
for {
hdr, err := tarReader.Next()
if err == io.EOF {
break
}
if err != nil {
return errors.Wrap(err, "failed to read tar data")
}
if hdr.Typeflag != tar.TypeReg {
continue
}
err = func() error {
fileName := filepath.Join(destDir, hdr.Name)
filePath, _ := filepath.Split(fileName)
err := os.MkdirAll(filePath, 0755)
if err != nil {
return errors.Wrapf(err, "failed to create directory %q", filePath)
}
fileWriter, err := os.Create(fileName)
if err != nil {
return errors.Wrapf(err, "failed to create file %q", hdr.Name)
}
defer fileWriter.Close()
_, err = io.Copy(fileWriter, tarReader)
if err != nil {
return errors.Wrapf(err, "failed to write file %q", hdr.Name)
}
return nil
}()
if err != nil {
return err
}
}
return nil
}