-
Notifications
You must be signed in to change notification settings - Fork 1
/
tar.go
135 lines (128 loc) · 2.47 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package building
import (
"archive/tar"
"compress/gzip"
"debug/elf"
"io"
"os"
"path/filepath"
)
func (b *B) Tar(args ...string) compression {
return makeCompression(Tar{}, args)
}
type Tar struct{}
func (t Tar) Write(w io.Writer, level int, dst string, srcs []fileset) error {
if dst != "-" {
f, err := os.Create(dst)
if err != nil {
return err
}
defer b.Close(f)
w = f
ext := filepath.Ext(dst)
if ext == ".gz" || ext == ".tgz" {
gz, err := gzip.NewWriterLevel(f, level)
if err != nil {
return err
}
defer b.Close(gz)
w = gz
}
}
tw := tar.NewWriter(w)
defer b.Close(tw)
return walk(srcs, func(path, rel string, info os.FileInfo) error {
return writeTar(tw, path, rel, info)
})
}
func writeTar(tw *tar.Writer, path, rel string, info os.FileInfo) error {
hdr, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
hdr.Name = rel
if hdr.Mode%2 == 0 && isExecutable(path) {
hdr.Mode++
b.Debugln("fixed execute permissions for", hdr.Name)
}
if err := tw.WriteHeader(hdr); err != nil {
return err
}
if info.IsDir() {
return nil
}
f, err := os.Open(path)
if err != nil {
return err
}
defer b.Close(f)
_, err = io.Copy(tw, f)
return err
}
func isExecutable(path string) bool {
if e, err := elf.Open(path); err == nil && e.Type == elf.ET_EXEC {
return true
}
if f, err := os.Open(path); err == nil {
buf := make([]byte, 2)
_, err = f.Read(buf)
if err == nil && buf[0] == '#' && buf[1] == '!' {
return true
}
}
return false
}
func untarFiles(src, dst string) error {
var r io.Reader
if src == "-" {
r = os.Stdin
} else {
f, err := os.Open(src)
if err != nil {
return err
}
defer b.Close(f)
r = f
ext := filepath.Ext(src)
if ext == ".gz" || ext == ".tgz" {
gz, err := gzip.NewReader(r)
if err != nil {
return err
}
defer b.Close(gz)
r = gz
}
}
tr := tar.NewReader(r)
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of compression
}
if err != nil {
return err
}
path := filepath.Join(dst, hdr.Name)
info := hdr.FileInfo()
if info.IsDir() {
if err = os.MkdirAll(path, info.Mode()); err != nil {
return err
}
continue
}
dir := filepath.Dir(path)
if err = os.MkdirAll(dir, 0755); err != nil {
return err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, info.Mode())
if err != nil {
return err
}
defer b.Close(f)
_, err = io.Copy(f, tr)
if err != nil {
return err
}
}
return nil
}