-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (72 loc) · 1.53 KB
/
main.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
package main
import (
"flag"
"fmt"
"os"
"sort"
"strings"
"github.com/mitchellh/goamz/aws"
"github.com/mitchellh/goamz/s3"
)
func main() {
var err error
var match = flag.String("match", "", "pattern to match when listing keys")
flag.Parse()
args := flag.Args()
auth, err := aws.SharedAuth()
if err != nil {
fmt.Fprintf(os.Stderr, "unable to authenticate: %s\n", err.Error())
os.Exit(1)
}
client := s3.New(auth, aws.USEast)
if len(args) == 0 {
err = listBuckets(client, *match)
} else {
err = listObjectsInBuckets(client, args, *match)
}
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
}
func listBuckets(client *s3.S3, match string) error {
resp, err := client.ListBuckets()
if err != nil {
return err
}
for _, bucket := range resp.Buckets {
if len(match) > 0 {
if strings.HasPrefix(bucket.Name, match) {
fmt.Printf("%s\n", bucket.Name)
}
} else {
fmt.Printf("%s\n", bucket.Name)
}
}
return nil
}
func listObjectsInBuckets(client *s3.S3, buckets []string, match string) error {
for _, b := range buckets {
bucket := client.Bucket(b)
contents, err := bucket.GetBucketContents()
if err != nil {
return err
}
matches := []string{}
for key, value := range *contents {
if len(match) > 0 {
if strings.HasPrefix(key, match) {
matches = append(matches, key)
}
} else {
fmt.Printf("%s (%d)\n", key, value.Size)
}
}
if len(match) > 0 {
sort.Strings(matches)
fmt.Printf("%s\n", matches[len(matches)-1])
}
return nil
}
return nil
}