-
Notifications
You must be signed in to change notification settings - Fork 19
/
storage_list.go
108 lines (87 loc) · 2.61 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
package cmd
import (
"fmt"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/exoscale/cli/pkg/globalstate"
"github.com/exoscale/cli/pkg/output"
"github.com/exoscale/cli/pkg/storage/sos"
"github.com/exoscale/egoscale"
)
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(output.TemplateAnnotations(&sos.ListBucketsItemOutput{}), ", "),
strings.Join(output.TemplateAnnotations(&sos.ListObjectsItemOutput{}), ", ")),
Aliases: gListAlias,
PreRun: func(cmd *cobra.Command, args []string) {
if len(args) == 1 {
args[0] = strings.TrimPrefix(args[0], sos.BucketPrefix)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
var (
bucket string
prefix string
)
if len(args) == 0 {
return printOutput(listStorageBuckets())
}
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 := sos.NewStorageClient(
gContext,
sos.ClientOptZoneFromBucket(gContext, bucket),
)
if err != nil {
return fmt.Errorf("unable to initialize storage client: %w", err)
}
return printOutput(storage.ListObjects(gContext, 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() (output.Outputter, error) {
out := make(sos.ListBucketsOutput, 0)
res, err := globalstate.EgoscaleClient.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, sos.ListBucketsItemOutput{
Name: b.Name,
Zone: b.Region,
Size: b.Usage,
Created: created.Format(sos.TimestampFormat),
})
}
return &out, nil
}