-
Notifications
You must be signed in to change notification settings - Fork 20
/
storage_list.go
225 lines (190 loc) · 5.49 KB
/
storage_list.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
package cmd
import (
"fmt"
"os"
"path"
"strings"
"text/tabwriter"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/dustin/go-humanize"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
type storageListObjectsItemOutput struct {
Path string `json:"name"`
Size int64 `json:"size"`
LastModified string `json:"last_modified,omitempty"`
Dir bool `json:"dir"`
}
type storageListObjectsOutput []storageListObjectsItemOutput
func (o *storageListObjectsOutput) toJSON() { outputJSON(o) }
func (o *storageListObjectsOutput) toText() { outputText(o) }
func (o *storageListObjectsOutput) toTable() {
table := tabwriter.NewWriter(os.Stdout,
0,
0,
1,
' ',
tabwriter.TabIndent)
defer table.Flush()
for _, f := range *o {
if f.Dir {
_, _ = fmt.Fprintf(table, " \tDIR \t%s/\n", f.Path)
} else {
_, _ = fmt.Fprintf(table, "%s\t%6s \t%s\n", f.LastModified, humanize.IBytes(uint64(f.Size)), f.Path)
}
}
}
type storageListBucketsItemOutput struct {
Name string `json:"name"`
Zone string `json:"zone"`
Size int64 `json:"size"`
Created string `json:"created"`
}
type storageListBucketsOutput []storageListBucketsItemOutput
func (o *storageListBucketsOutput) toJSON() { outputJSON(o) }
func (o *storageListBucketsOutput) toText() { outputText(o) }
func (o *storageListBucketsOutput) toTable() {
table := tabwriter.NewWriter(os.Stdout,
0,
0,
1,
' ',
tabwriter.TabIndent)
defer table.Flush()
for _, b := range *o {
_, _ = fmt.Fprintf(table, "%s\t%s\t%6s \t%s/\n",
b.Created, b.Zone, humanize.IBytes(uint64(b.Size)), b.Name)
}
}
var storageListCmd = &cobra.Command{
Use: "list [sos://BUCKET[/[PREFIX/]]",
Short: "List buckets and objects",
Long: fmt.Sprintf(`This command lists buckets and their objects.
If no argument is passed, this commands lists existing buckets. If a prefix is
specified (e.g. "sos://my-bucket/.../") the command lists the objects stored
in the bucket under the corresponding prefix.
Supported output template annotations:
* When listing buckets: %s
* When listing objects: %s`,
strings.Join(outputterTemplateAnnotations(&storageListBucketsItemOutput{}), ", "),
strings.Join(outputterTemplateAnnotations(&storageListObjectsItemOutput{}), ", ")),
Aliases: gListAlias,
PreRun: func(cmd *cobra.Command, args []string) {
if len(args) == 1 {
args[0] = strings.TrimPrefix(args[0], storageBucketPrefix)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
bucket string
prefix string
)
if len(args) == 0 {
return output(listStorageBuckets())
}
certsFile, err := cmd.Flags().GetString("certs-file")
if err != nil {
return err
}
recursive, err := cmd.Flags().GetBool("recursive")
if err != nil {
return err
}
stream, err := cmd.Flags().GetBool("stream")
if err != nil {
return err
}
parts := strings.SplitN(args[0], "/", 2)
bucket = parts[0]
if len(parts) > 1 {
prefix = parts[1]
}
storage, err := newStorageClient(
storageClientOptWithCertsFile(certsFile),
storageClientOptZoneFromBucket(bucket),
)
if err != nil {
return fmt.Errorf("unable to initialize storage client: %w", err)
}
return output(storage.listObjects(bucket, prefix, recursive, stream))
},
}
func init() {
storageListCmd.Flags().BoolP("recursive", "r", false,
"list bucket recursively")
storageListCmd.Flags().BoolP("stream", "s", false,
"stream listed files instead of waiting for complete listing (useful for large buckets)")
storageCmd.AddCommand(storageListCmd)
}
func listStorageBuckets() (outputter, error) {
out := make(storageListBucketsOutput, 0)
res, err := cs.RequestWithContext(gContext, egoscale.ListBucketsUsage{})
if err != nil {
return nil, err
}
for _, b := range res.(*egoscale.ListBucketsUsageResponse).BucketsUsage {
created, err := time.Parse(time.RFC3339, b.Created)
if err != nil {
return nil, err
}
out = append(out, storageListBucketsItemOutput{
Name: b.Name,
Zone: b.Region,
Size: b.Usage,
Created: created.Format(storageTimestampFormat),
})
}
return &out, nil
}
func (c *storageClient) listObjects(bucket, prefix string, recursive, stream bool) (outputter, error) {
dirs := make(map[string]struct{})
out := make(storageListObjectsOutput, 0)
var ct string
for {
res, err := c.ListObjectsV2(gContext, &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
Prefix: aws.String(prefix),
ContinuationToken: aws.String(ct),
})
if err != nil {
return nil, err
}
ct = aws.ToString(res.NextContinuationToken)
for _, o := range res.Contents {
// If not invoked in recursive mode, split object keys on the "/" separator then return
// a "directory" placeholder for the base prefix and hide objects "below" the prefix.
parts := strings.SplitN(strings.TrimPrefix(aws.ToString(o.Key), prefix), "/", 2)
if len(parts) > 1 && !recursive {
dir := path.Base(parts[0])
if _, ok := dirs[dir]; !ok {
if stream {
fmt.Println(dir + "/")
} else {
out = append(out, storageListObjectsItemOutput{
Path: dir,
Dir: true,
})
}
dirs[dir] = struct{}{}
}
continue
}
if stream {
fmt.Println(aws.ToString(o.Key))
} else {
out = append(out, storageListObjectsItemOutput{
Path: aws.ToString(o.Key),
Size: o.Size,
LastModified: o.LastModified.Format(storageTimestampFormat),
})
}
}
if !res.IsTruncated {
break
}
}
return &out, nil
}