-
Notifications
You must be signed in to change notification settings - Fork 7
/
util.go
324 lines (272 loc) · 7.99 KB
/
util.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package pail
import (
"archive/tar"
"context"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/mongodb/grip"
"github.com/pkg/errors"
)
func consistentJoin(elems []string) string {
return filepath.ToSlash(filepath.Join(elems...))
}
func consistentTrimPrefix(key, prefix string) string {
return strings.TrimPrefix(key, prefix+"/")
}
func walkLocalTree(ctx context.Context, prefix string) ([]string, error) {
var out []string
err := filepath.Walk(prefix, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if ctx.Err() != nil {
return errors.New("operation canceled")
}
rel, err := filepath.Rel(prefix, path)
if err != nil {
return errors.Wrap(err, "getting relative path")
}
if info.Mode()&os.ModeSymlink != 0 {
symPath, err := filepath.EvalSymlinks(path)
if err != nil {
return errors.Wrap(err, "getting symlink path")
}
symTree, err := walkLocalTree(ctx, symPath)
if err != nil {
return errors.Wrap(err, "getting symlink tree")
}
for i := range symTree {
symTree[i] = filepath.Join(rel, symTree[i])
}
out = append(out, symTree...)
return nil
}
if info.IsDir() {
return nil
}
out = append(out, rel)
return nil
})
if err != nil {
return nil, errors.Wrap(err, "finding files")
}
if ctx.Err() != nil {
return nil, errors.New("operation canceled")
}
return out, nil
}
func removePrefix(ctx context.Context, prefix string, b Bucket) error {
iter, err := b.List(ctx, prefix)
if err != nil {
return errors.Wrapf(err, "listing objects with prefix '%s'", prefix)
}
keys := []string{}
for iter.Next(ctx) {
keys = append(keys, iter.Item().Name())
}
return errors.Wrapf(b.RemoveMany(ctx, keys...), "deleting objects with prefix '%s'", prefix)
}
func removeMatching(ctx context.Context, expression string, b Bucket) error {
regex, err := regexp.Compile(expression)
if err != nil {
return errors.Wrapf(err, "invalid regular expression '%s'", expression)
}
iter, err := b.List(ctx, "")
if err != nil {
return errors.Wrapf(err, "listing objects matching '%s'", expression)
}
keys := []string{}
for iter.Next(ctx) {
key := iter.Item().Name()
if regex.MatchString(key) {
keys = append(keys, key)
}
}
return errors.Wrapf(b.RemoveMany(ctx, keys...), "deleting objects matching '%s'", expression)
}
func deleteOnPush(ctx context.Context, sourceFiles []string, remote string, bucket Bucket) error {
sourceFilesMap := map[string]bool{}
for _, fn := range sourceFiles {
// Add the remote prefix and use the bucket's Join method to
// ensure that we are correctly matching remote keys with local
// filenames.
sourceFilesMap[bucket.Join(remote, fn)] = true
}
iter, err := bucket.List(ctx, remote)
if err != nil {
return err
}
toDelete := []string{}
for iter.Next(ctx) {
name := iter.Item().Name()
if !sourceFilesMap[name] {
toDelete = append(toDelete, name)
}
}
return bucket.RemoveMany(ctx, toDelete...)
}
func deleteOnPull(ctx context.Context, sourceFiles []string, local string) error {
sourceFilesMap := map[string]bool{}
for _, fn := range sourceFiles {
sourceFilesMap[fn] = true
}
destinationFiles, err := walkLocalTree(ctx, local)
if err != nil {
return errors.WithStack(err)
}
catcher := grip.NewBasicCatcher()
for _, fn := range destinationFiles {
if !sourceFilesMap[fn] {
catcher.Add(os.RemoveAll(filepath.Join(local, fn)))
}
}
return catcher.Resolve()
}
// The archive/unarchive functions below are modified versions of the same
// functions from github.com/mholt/archiver.
func tarFile(tarWriter *tar.Writer, dir, relPath string) error {
var absPath string
if filepath.IsAbs(relPath) {
if !strings.HasPrefix(relPath, dir) {
return errors.Errorf("cannot specify absolute path to file that is not within directory '%s'", dir)
}
absPath = relPath
var err error
relPath, err = filepath.Rel(dir, relPath)
if err != nil {
return errors.Wrap(err, "getting relative path")
}
} else {
absPath = filepath.Join(dir, relPath)
}
info, err := os.Stat(absPath)
if err != nil {
return errors.Wrapf(err, "getting stat info for path '%s'", absPath)
}
var file *os.File
if info.Mode().IsRegular() {
file, err = os.Open(absPath)
if err != nil {
return errors.Wrap(err, "opening file")
}
defer file.Close()
}
if err := addToTar(tarWriter, info, file, absPath, relPath); err != nil {
return errors.Wrap(err, "adding file to archive")
}
return nil
}
func addToTar(tarWriter *tar.Writer, info os.FileInfo, content io.Reader, absPath, relPath string) error {
header, err := tar.FileInfoHeader(info, absPath)
if err != nil {
return errors.Wrap(err, "creating header")
}
header.Name = filepath.ToSlash(relPath)
if info.IsDir() {
header.Name += "/"
}
if err := tarWriter.WriteHeader(header); err != nil {
return errors.Wrap(err, "writing header")
}
if header.Typeflag == tar.TypeReg {
if _, err := io.CopyN(tarWriter, content, info.Size()); err != nil && err != io.EOF {
return errors.Wrap(err, "archiving contents")
}
}
return nil
}
func untar(tarReader *tar.Reader, destination string, exclude *regexp.Regexp) error {
for {
header, err := tarReader.Next()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if exclude != nil && exclude.MatchString(header.Name) {
continue
}
if err := untarFile(tarReader, header, destination); err != nil {
return errors.Wrap(err, header.Name)
}
}
}
// untarFile untars a single file from the tar reader with header header into destination.
func untarFile(tarReader *tar.Reader, header *tar.Header, destination string) error {
err := sanitizeExtractPath(header.Name, destination)
if err != nil {
return err
}
destpath := filepath.Join(destination, header.Name)
switch header.Typeflag {
case tar.TypeDir:
return mkdir(destpath)
case tar.TypeReg, tar.TypeRegA, tar.TypeChar, tar.TypeBlock, tar.TypeFifo:
return writeFile(destpath, tarReader, header.FileInfo().Mode())
case tar.TypeSymlink:
return writeSymlink(destpath, header.Linkname)
case tar.TypeLink:
return writeHardLink(destpath, filepath.Join(destination, header.Linkname))
case tar.TypeXGlobalHeader:
// ignore the pax global header from git generated tarballs
return nil
default:
return errors.Errorf("unknown type flag %c", header.Typeflag)
}
}
func sanitizeExtractPath(filePath string, destination string) error {
// to avoid zip slip (writing outside of the destination), we resolve
// the target path, and make sure it's nested in the intended
// destination, or bail otherwise.
destpath := filepath.Join(destination, filePath)
if !strings.HasPrefix(destpath, filepath.Clean(destination)) {
return errors.Errorf("illegal file path '%s'", filePath)
}
return nil
}
func mkdir(dirPath string) error {
if err := os.MkdirAll(dirPath, 0755); err != nil {
return errors.Wrapf(err, "making directory '%s'", dirPath)
}
return nil
}
func writeFile(path string, content io.Reader, mode os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return errors.Wrapf(err, "making parent directories for file '%s'", path)
}
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0700)
if err != nil {
return err
}
defer file.Close()
if err = file.Chmod(mode); err != nil && runtime.GOOS != "windows" {
return err
}
if _, err = io.Copy(file, content); err != nil {
return err
}
return nil
}
func writeSymlink(path string, target string) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return errors.Wrapf(err, "making parent directories for file '%s'", path)
}
if err := os.Symlink(target, path); err != nil {
return errors.Wrapf(err, "making symbolic link for path '%s'", path)
}
return nil
}
func writeHardLink(path string, target string) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return errors.Wrapf(err, "making parent directories for file '%s'", path)
}
if err := os.Link(target, path); err != nil {
return errors.Wrapf(err, "making hard link for '%s'", path)
}
return nil
}