/
util.go
102 lines (94 loc) · 2.62 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
// Copyright 2020 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"context"
"io/ioutil"
"go.uber.org/multierr"
)
// ReadPath is analogous to ioutil.ReadFile.
//
// Returns an error that fufills IsNotExist if the path does not exist.
func ReadPath(ctx context.Context, readBucket ReadBucket, path string) (_ []byte, retErr error) {
readObject, err := readBucket.Get(ctx, path)
if err != nil {
return nil, err
}
defer func() {
if err := readObject.Close(); err != nil && retErr == nil {
retErr = err
}
}()
return ioutil.ReadAll(readObject)
}
// PutPath puts the data at the path.
func PutPath(ctx context.Context, writeBucket WriteBucket, path string, data []byte) (retErr error) {
writeObject, err := writeBucket.Put(ctx, path)
if err != nil {
return err
}
defer func() {
retErr = multierr.Append(retErr, writeObject.Close())
}()
_, err = writeObject.Write(data)
return err
}
// WalkReadObjects walks the bucket and calls get on each, closing the resulting ReadObjectCloser
// when done.
func WalkReadObjects(
ctx context.Context,
readBucket ReadBucket,
prefix string,
f func(ReadObject) error,
) error {
return readBucket.Walk(
ctx,
prefix,
func(objectInfo ObjectInfo) error {
readObjectCloser, err := readBucket.Get(ctx, objectInfo.Path())
if err != nil {
return err
}
return multierr.Append(f(readObjectCloser), readObjectCloser.Close())
},
)
}
// AllPaths walks the bucket and gets all the paths.
func AllPaths(ctx context.Context, readBucket ReadBucket, prefix string) ([]string, error) {
var allPaths []string
if err := readBucket.Walk(
ctx,
prefix,
func(objectInfo ObjectInfo) error {
allPaths = append(allPaths, objectInfo.Path())
return nil
},
); err != nil {
return nil, err
}
return allPaths, nil
}
// Exists returns true if the path exists, false otherwise.
//
// Returns error on system error.
func Exists(ctx context.Context, readBucket ReadBucket, path string) (bool, error) {
_, err := readBucket.Stat(ctx, path)
if err != nil {
if IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}