-
Notifications
You must be signed in to change notification settings - Fork 0
/
tar.go
101 lines (82 loc) · 1.95 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package filecache
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"path/filepath"
"time"
"go.uber.org/zap"
)
// Tar gzips and tars encoded data retrieved from
// the filecaches and writes it to w.
func Tar(w io.Writer, fileCaches ...Queue) error {
gzipWriter := gzip.NewWriter(w)
defer gzipWriter.Close() // nolint: errcheck
tarWriter := tar.NewWriter(gzipWriter)
defer tarWriter.Close() // nolint: errcheck
for _, f := range fileCaches {
partReader, partSize, err := f.EncodeToReader()
if err != nil {
if err == ErrNilType {
continue
}
return err
}
closeReader := func() {
if partCloser, ok := partReader.(io.Closer); ok {
if errClose := partCloser.Close(); errClose != nil {
zap.L().Debug("failed to close file during tar for "+f.Name(), zap.Error(errClose))
}
}
}
header := &tar.Header{
Name: f.Name(),
Size: partSize,
Mode: 0666,
ModTime: time.Now(),
}
if err := tarWriter.WriteHeader(header); err != nil {
closeReader()
return err
}
if _, err = io.Copy(tarWriter, partReader); err != nil {
closeReader()
return err
}
closeReader()
}
return nil
}
// Untar reads data from the reader r and writes it
// to the destDir as independent files. It is upto
// the caller to make sure directory exists.
func Untar(destDir string, r io.Reader) error {
gzipReader, err := gzip.NewReader(r)
if err != nil {
return err
}
defer gzipReader.Close() // nolint: errcheck
tarReader := tar.NewReader(gzipReader)
for {
header, err := tarReader.Next()
switch err {
case nil:
// Do nothing.
case io.EOF:
return nil
default:
return err
}
dest := filepath.Join(destDir, header.Name)
file, err := os.OpenFile(dest, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, header.FileInfo().Mode())
if err != nil {
return err
}
if _, err = io.Copy(file, tarReader); err != nil {
file.Close() // nolint: errcheck
return err
}
file.Close() // nolint: errcheck
}
}