forked from buildpacks/pack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tar_builder.go
94 lines (78 loc) · 1.69 KB
/
tar_builder.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
package archive
import (
"archive/tar"
"io"
"os"
"time"
"github.com/pkg/errors"
"github.com/buildpacks/pack/internal/style"
)
type TarBuilder struct {
files []fileEntry
}
type fileEntry struct {
typeFlag byte
path string
mode int64
modTime time.Time
contents []byte
}
func (t *TarBuilder) AddFile(path string, mode int64, modTime time.Time, contents []byte) {
t.files = append(t.files, fileEntry{
typeFlag: tar.TypeReg,
path: path,
mode: mode,
modTime: modTime,
contents: contents,
})
}
func (t *TarBuilder) AddDir(path string, mode int64, modTime time.Time) {
t.files = append(t.files, fileEntry{
typeFlag: tar.TypeDir,
path: path,
mode: mode,
modTime: modTime,
})
}
func (t *TarBuilder) Reader(twf TarWriterFactory) io.ReadCloser {
pr, pw := io.Pipe()
go func() {
var err error
defer func() {
pw.CloseWithError(err)
}()
_, err = t.WriteTo(pw, twf)
}()
return pr
}
func (t *TarBuilder) WriteToPath(path string, twf TarWriterFactory) error {
fh, err := os.Create(path)
if err != nil {
return errors.Wrapf(err, "create file for tar: %s", style.Symbol(path))
}
defer fh.Close()
_, err = t.WriteTo(fh, twf)
return err
}
func (t *TarBuilder) WriteTo(w io.Writer, twf TarWriterFactory) (int64, error) {
var written int64
tw := twf.NewWriter(w)
defer tw.Close()
for _, f := range t.files {
if err := tw.WriteHeader(&tar.Header{
Typeflag: f.typeFlag,
Name: f.path,
Size: int64(len(f.contents)),
Mode: f.mode,
ModTime: f.modTime,
}); err != nil {
return written, err
}
n, err := tw.Write(f.contents)
if err != nil {
return written, err
}
written += int64(n)
}
return written, nil
}