-
Notifications
You must be signed in to change notification settings - Fork 7
/
rm.go
106 lines (84 loc) · 2.05 KB
/
rm.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
package cliaws
import (
"context"
"fmt"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/alexflint/go-arg"
"github.com/nathants/libaws/lib"
)
func init() {
lib.Commands["s3-rm"] = s3Rm
lib.Args["s3-rm"] = s3RmArgs{}
}
type s3RmArgs struct {
Path string `arg:"positional,required"`
Version string `arg:"-v,--version"`
Recursive bool `arg:"-r,--recursive"`
Preview bool `arg:"-p,--preview"`
}
func (s3RmArgs) Description() string {
return "\nrm s3 content \n"
}
func s3Rm() {
var args s3RmArgs
arg.MustParse(&args)
ctx := context.Background()
args.Path = strings.ReplaceAll(args.Path, "s3://", "")
bucket, key, err := lib.SplitOnce(args.Path, "/")
if err != nil {
lib.Logger.Fatal("error: ", err)
}
s3Client, err := lib.S3ClientBucketRegion(bucket)
if err != nil {
lib.Logger.Fatal("error: ", err)
}
var delimiter *string
if !args.Recursive {
delimiter = aws.String("/")
}
var token *string
for {
out, err := s3Client.ListObjectsV2WithContext(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(bucket),
Prefix: aws.String(key),
Delimiter: delimiter,
ContinuationToken: token,
})
if err != nil {
lib.Logger.Fatal("error: ", err)
}
var objects []*s3.ObjectIdentifier
for _, obj := range out.Contents {
objects = append(objects, &s3.ObjectIdentifier{
Key: obj.Key,
})
}
if len(objects) != 0 {
if !args.Preview {
deleteOut, err := s3Client.DeleteObjectsWithContext(ctx, &s3.DeleteObjectsInput{
Bucket: aws.String(bucket),
Delete: &s3.Delete{Objects: objects},
})
if err != nil {
lib.Logger.Fatal("error: ", err)
}
for _, err := range deleteOut.Errors {
fmt.Println("error:", *err.Key, *err.Code, *err.Message)
}
if len(deleteOut.Errors) != 0 {
os.Exit(1)
}
}
for _, object := range objects {
fmt.Println(lib.PreviewString(args.Preview)+"s3 deleted:", *object.Key)
}
}
if !*out.IsTruncated {
break
}
token = out.NextContinuationToken
}
}