-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtarinator.go
148 lines (115 loc) · 2.46 KB
/
tarinator.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
136
137
138
139
140
141
142
143
144
145
146
147
148
package tarinator
import (
"archive/tar"
"compress/gzip"
"io"
"log"
"os"
"path/filepath"
"strings"
)
func Tarinate(paths []string, tarPath string) error {
file, err := os.Create(tarPath)
if err != nil {
return err
}
defer file.Close()
var fileReader io.WriteCloser = file
if strings.HasSuffix(tarPath, ".gz") {
fileReader = gzip.NewWriter(file)
defer fileReader.Close()
}
tw := tar.NewWriter(fileReader)
defer tw.Close()
for _, i := range paths {
if err := tarwalk(i, "", tw); err != nil {
return err
}
}
return nil
}
func tarwalk(source, target string, tw *tar.Writer) error {
info, err := os.Stat(source)
if err != nil {
return nil
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
return filepath.Walk(source,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.ToSlash(filepath.Join(baseDir, strings.TrimPrefix(path, source)))
}
if err := tw.WriteHeader(header); err != nil {
return err
}
if info.IsDir() {
return nil
}
if !info.Mode().IsRegular() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tw, file)
return err
})
}
func UnTarinate(extractPath, sourcefile string) error {
file, err := os.Open(sourcefile)
if err != nil {
return err
}
defer file.Close()
var fileReader io.ReadCloser = file
if strings.HasSuffix(sourcefile, ".gz") {
if fileReader, err = gzip.NewReader(file); err != nil {
return err
}
defer fileReader.Close()
}
tarBallReader := tar.NewReader(fileReader)
for {
header, err := tarBallReader.Next()
if err != nil {
if err == io.EOF {
break
}
return err
}
filename := filepath.Join(extractPath, filepath.FromSlash(header.Name))
switch header.Typeflag {
case tar.TypeDir:
err = os.MkdirAll(filename, os.FileMode(header.Mode)) // or use 0755 if you prefer
if err != nil {
return err
}
case tar.TypeReg:
writer, err := os.Create(filename)
if err != nil {
return err
}
io.Copy(writer, tarBallReader)
err = os.Chmod(filename, os.FileMode(header.Mode))
if err != nil {
return err
}
writer.Close()
default:
log.Printf("Unable to untar type: %c in file %s", header.Typeflag, filename)
}
}
return nil
}