-
Notifications
You must be signed in to change notification settings - Fork 410
Expand file tree
/
Copy pathtar.go
More file actions
294 lines (242 loc) · 7.55 KB
/
tar.go
File metadata and controls
294 lines (242 loc) · 7.55 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package server
import (
"archive/tar"
"compress/gzip"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"github.com/loft-sh/devspace/pkg/util/fsutil"
"github.com/pkg/errors"
)
type fileInformation struct {
Name string
Size int64
Mtime time.Time
}
func untarAll(reader io.ReadCloser, options *UpstreamOptions) error {
defer reader.Close()
gzr, err := gzip.NewReader(reader)
if err != nil {
return errors.Errorf("error decompressing: %v", err)
}
defer gzr.Close()
tarReader := tar.NewReader(gzr)
for {
shouldContinue, err := untarNext(tarReader, options)
if err != nil {
return errors.Wrap(err, "decompress")
} else if !shouldContinue {
return nil
}
}
}
func createAllFolders(name string, perm os.FileMode, options *UpstreamOptions) error {
absPath, err := filepath.Abs(name)
if err != nil {
return err
}
slashPath := filepath.ToSlash(absPath)
pathParts := strings.Split(slashPath, "/")
for i := 1; i < len(pathParts); i++ {
dirToCreate := strings.Join(pathParts[:i+1], "/")
err := os.Mkdir(dirToCreate, perm)
if err != nil {
if os.IsExist(err) {
continue
}
return errors.Errorf("error creating %s: %v", dirToCreate, err)
}
if options.DirCreateCmd != "" {
cmdArgs := make([]string, 0, len(options.DirCreateArgs))
for _, arg := range options.DirCreateArgs {
if arg == "{}" {
cmdArgs = append(cmdArgs, dirToCreate)
} else {
cmdArgs = append(cmdArgs, arg)
}
}
out, err := exec.Command(options.DirCreateCmd, cmdArgs...).CombinedOutput()
if err != nil {
return errors.Errorf("error executing command '%s %s': %s => %v", options.DirCreateCmd, strings.Join(cmdArgs, " "), string(out), err)
}
}
}
return nil
}
func untarNext(tarReader *tar.Reader, options *UpstreamOptions) (bool, error) {
header, err := tarReader.Next()
if err != nil {
if err != io.EOF {
return false, errors.Wrap(err, "tar reader next")
}
return false, nil
}
relativePath := getRelativeFromFullPath("/"+header.Name, "")
outFileName := path.Join(options.UploadPath, relativePath)
baseName := path.Dir(outFileName)
// Check if newer file is there and then don't override?
stat, _ := os.Stat(outFileName)
if err := createAllFolders(baseName, 0755, options); err != nil {
return false, err
}
if header.FileInfo().IsDir() {
if err := createAllFolders(outFileName, 0755, options); err != nil {
return false, err
}
return true, nil
}
// Create / Override file
outFile, err := os.Create(outFileName)
if err != nil {
// Try again after 5 seconds
time.Sleep(time.Second * 5)
outFile, err = os.Create(outFileName)
if err != nil {
return false, errors.Wrapf(err, "create %s", outFileName)
}
}
defer outFile.Close()
if _, err := io.Copy(outFile, tarReader); err != nil {
return false, errors.Wrapf(err, "io copy tar reader %s", outFileName)
}
if err := outFile.Close(); err != nil {
return false, errors.Wrapf(err, "out file close %s", outFileName)
}
// Set old permissions and owner and group
if stat != nil {
if options.OverridePermission {
// Set permissions
_ = os.Chmod(outFileName, header.FileInfo().Mode())
} else {
// Set old permissions correctly
_ = os.Chmod(outFileName, stat.Mode())
}
// Set old owner & group correctly
_ = Chown(outFileName, stat)
} else {
// Set permissions
_ = os.Chmod(outFileName, header.FileInfo().Mode())
}
// Set mod time from tar header
_ = os.Chtimes(outFileName, time.Now(), header.FileInfo().ModTime())
// Execute command if defined
if options.FileChangeCmd != "" {
cmdArgs := make([]string, 0, len(options.FileChangeArgs))
for _, arg := range options.FileChangeArgs {
if arg == "{}" {
cmdArgs = append(cmdArgs, outFileName)
} else {
cmdArgs = append(cmdArgs, arg)
}
}
out, err := exec.Command(options.FileChangeCmd, cmdArgs...).CombinedOutput()
if err != nil {
return false, errors.Errorf("error executing command '%s %s': %s => %v", options.FileChangeCmd, strings.Join(cmdArgs, " "), string(out), err)
}
}
return true, nil
}
func recursiveTar(basePath, relativePath string, writtenFiles map[string]bool, tw *tar.Writer, skipFolderContents bool) error {
absFilepath := path.Join(basePath, relativePath)
if _, ok := writtenFiles[relativePath]; ok {
return nil
}
// We skip files that are suddenly not there anymore
stat, err := os.Stat(absFilepath)
if err != nil {
// File is suddenly not here anymore is ignored
return nil
}
fileInformation := createFileInformationFromStat(relativePath, stat)
if stat.IsDir() {
// Recursively tar folder
return tarFolder(basePath, fileInformation, writtenFiles, stat, tw, skipFolderContents)
}
return tarFile(basePath, fileInformation, writtenFiles, stat, tw)
}
func tarFolder(basePath string, fileInformation *fileInformation, writtenFiles map[string]bool, stat os.FileInfo, tw *tar.Writer, skipContents bool) error {
filepath := path.Join(basePath, fileInformation.Name)
files, err := os.ReadDir(filepath)
if err != nil {
// Ignore this error because it could happen the file is suddenly not there anymore
return nil
}
if skipContents || (len(files) == 0 && fileInformation.Name != "") {
// Case empty directory
hdr, _ := tar.FileInfoHeader(stat, filepath)
hdr.Name = fileInformation.Name
hdr.ModTime = fileInformation.Mtime
if err := tw.WriteHeader(hdr); err != nil {
return errors.Wrapf(err, "tw write header %s", filepath)
}
writtenFiles[fileInformation.Name] = true
}
if !skipContents {
for _, dirEntry := range files {
f, err := dirEntry.Info()
if err != nil {
continue
}
if fsutil.IsRecursiveSymlink(f, path.Join(fileInformation.Name, f.Name())) {
continue
}
if err := recursiveTar(basePath, path.Join(fileInformation.Name, f.Name()), writtenFiles, tw, skipContents); err != nil {
return errors.Wrap(err, "recursive tar")
}
}
}
return nil
}
func tarFile(basePath string, fileInformation *fileInformation, writtenFiles map[string]bool, stat os.FileInfo, tw *tar.Writer) error {
var err error
filepath := path.Join(basePath, fileInformation.Name)
if fsutil.IsSymlink(stat.Mode()) {
if filepath, err = os.Readlink(filepath); err != nil {
return nil
}
}
// Case regular file
f, err := os.Open(filepath)
if err != nil {
// We ignore this error here because it could happen that the file is suddenly not here anymore
return nil
}
defer f.Close()
hdr, err := tar.FileInfoHeader(stat, filepath)
if err != nil {
return errors.Wrapf(err, "tar file info header %s", filepath)
}
hdr.Name = fileInformation.Name
// We have to cut of the nanoseconds otherwise this sometimes leads to issues on the client side
// because the unix value will be rounded up
hdr.ModTime = time.Unix(fileInformation.Mtime.Unix(), 0)
if err := tw.WriteHeader(hdr); err != nil {
return errors.Wrapf(err, "tw write header %s", filepath)
}
// nothing more to do for non-regular
if !stat.Mode().IsRegular() {
return nil
}
if copied, err := io.CopyN(tw, f, stat.Size()); err != nil {
return errors.Wrapf(err, "io copy %s", filepath)
} else if copied != stat.Size() {
return errors.New("tar: file truncated during read")
}
writtenFiles[fileInformation.Name] = true
return nil
}
func getRelativeFromFullPath(fullpath string, prefix string) string {
return strings.TrimPrefix(strings.ReplaceAll(strings.ReplaceAll(fullpath[len(prefix):], "\\", "/"), "//", "/"), ".")
}
func createFileInformationFromStat(relativePath string, stat os.FileInfo) *fileInformation {
fileInformation := &fileInformation{
Name: relativePath,
Size: stat.Size(),
Mtime: stat.ModTime(),
}
return fileInformation
}