forked from fujiwara/awslim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
299 lines (268 loc) · 7.11 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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package sdkclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/alecthomas/kong"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/google/go-jsonnet"
"github.com/jmespath/go-jmespath"
)
var Version = "HEAD"
var clientMethods = make(map[string]ClientMethod)
type ClientMethod func(context.Context, *clientMethodParam) (any, error)
var ErrDryRun = fmt.Errorf("dry-run mode")
type CLI struct {
Service string `arg:"" help:"service name" default:""`
Method string `arg:"" help:"method name" default:""`
Input string `arg:"" help:"input JSON/Jsonnet struct or filename" default:"{}"`
InputStream string `short:"i" help:"bind input filename or '-' to io.Reader field in the input struct"`
OutputStream string `short:"o" help:"bind output filename or '-' to io.ReadCloser field in the output struct"`
APIOutput bool `help:"output API response into stdout" default:"true" negatable:"true"`
RawOutput bool `short:"r" help:"output raw strings, not JSON texts"`
Compact bool `short:"c" help:"compact JSON output"`
Query string `short:"q" help:"JMESPath query to apply to output"`
ExtStr map[string]string `help:"external variables for Jsonnet"`
ExtCode map[string]string `help:"external code for Jsonnet"`
Strict bool `name:"strict" help:"strict input JSON unmarshaling" default:"true" negatable:"true"`
FollowNext string `short:"f" help:"OutputField=InputField format. follow the next token." default:""`
DryRun bool `short:"n" help:"dry-run mode"`
Version bool `short:"v" help:"show version"`
w io.Writer
}
func Run(ctx context.Context) error {
var c CLI
c.w = os.Stdout
kong.Parse(&c)
return c.Dispatch(ctx)
}
func (c *CLI) Dispatch(ctx context.Context) error {
if c.Version {
fmt.Fprintf(c.w, "aws-sdk-client-go %s\n", Version)
return nil
}
if c.Service == "" {
return c.ListServices(ctx)
} else if c.Method == "" {
return c.ListMethods(ctx)
} else {
return c.CallMethod(ctx)
}
}
func (c *CLI) SetWriter(w io.Writer) {
c.w = w
}
func (c *CLI) CallMethod(ctx context.Context) error {
method := kebabToCamel(c.Method)
key := buildKey(c.Service, method)
fn := clientMethods[key]
if fn == nil {
return fmt.Errorf("unknown function %s", key)
}
if c.Input == "help" {
fmt.Fprintf(c.w, "See https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/%s\n", key)
return nil
}
p, err := c.clientMethodParam(ctx)
if err != nil {
return err
}
defer p.Cleanup()
cont := true
for cont {
out, err := fn(ctx, p)
if err != nil {
if err == ErrDryRun {
fmt.Fprintf(c.w, "dry-run: %s will be called with:\n%s", key, string(p.InputBytes))
return nil
}
return fmt.Errorf("failed to call %s: %w", key, err)
}
if err := c.output(ctx, out); err != nil {
return err
}
cont, err = p.FollowNext(out)
if err != nil {
return fmt.Errorf("failed to follow next token: %w", err)
}
}
return nil
}
func (c *CLI) output(_ context.Context, out any) error {
if !c.APIOutput {
return nil
}
var err error
if c.Query != "" {
out, err = jmespath.Search(c.Query, out)
if err != nil {
return fmt.Errorf("failed to apply JMESPath query: %w", err)
}
}
if c.RawOutput {
switch t := out.(type) {
case string:
fmt.Fprintln(c.w, t)
return nil
case *string:
fmt.Fprintln(c.w, aws.ToString(t))
return nil
default:
// do nothing. output as JSON
}
}
b, err := json.Marshal(out)
if err != nil {
return fmt.Errorf("failed to marshal response: %w", err)
}
if !c.Compact {
var buf bytes.Buffer
json.Indent(&buf, b, "", " ")
buf.WriteString("\n")
buf.WriteTo(c.w)
} else {
io.WriteString(c.w, string(b))
}
return nil
}
func (c *CLI) loadInput(_ context.Context) ([]byte, error) {
var input []byte
vm := jsonnet.MakeVM()
for k, v := range c.ExtStr {
vm.ExtVar(k, v)
}
for k, v := range c.ExtCode {
vm.ExtCode(k, v)
}
if strings.HasPrefix(c.Input, "{") {
// string is JSON or Jsonnet
s, err := vm.EvaluateAnonymousSnippet("input", c.Input)
if err != nil {
return nil, fmt.Errorf("failed to evaluate Jsonnet: %w", err)
}
input = []byte(s)
} else {
// string is filename
s, err := vm.EvaluateFile(c.Input)
if err != nil {
return nil, fmt.Errorf("failed to evaluate Jsonnet: %w", err)
}
input = []byte(s)
}
return input, nil
}
func (c *CLI) clientMethodParam(ctx context.Context) (*clientMethodParam, error) {
awsCfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return nil, err
}
input, err := c.loadInput(ctx)
if err != nil {
return nil, err
}
p := &clientMethodParam{
awsCfg: awsCfg,
InputBytes: input,
InputReader: nil,
OutputWriter: nil,
DryRun: c.DryRun,
Strict: c.Strict,
}
p.SetNextToken(c.FollowNext)
switch c.InputStream {
case "":
// do nothing
case "-": // stdin
buf := &bytes.Buffer{}
if _, err := io.Copy(buf, os.Stdin); err != nil {
if err != io.EOF {
return nil, fmt.Errorf("failed to read from stdin: %w", err)
}
}
p.InputReader = buf
p.InputReaderLength = aws.Int64(int64(buf.Len()))
default:
f, err := os.Open(c.InputStream)
if err != nil {
return nil, fmt.Errorf("failed to open input file: %w", err)
}
p.InputReader = f
p.cleanup = append(p.cleanup, f.Close)
st, err := f.Stat()
if err != nil {
return nil, fmt.Errorf("failed to stat input file: %w", err)
}
p.InputReaderLength = aws.Int64(st.Size())
}
switch c.OutputStream {
case "":
// do nothing
case "-": // stdout
p.OutputWriter = os.Stdout
default:
f, err := os.Create(c.OutputStream)
if err != nil {
return nil, fmt.Errorf("failed to create output file: %w", err)
}
p.OutputWriter = f
p.cleanup = append(p.cleanup, f.Close)
}
return p, nil
}
func (c *CLI) ListMethods(_ context.Context) error {
methods := make([]string, 0)
for name := range clientMethods {
service, method := parseKey(name)
if service == c.Service {
methods = append(methods, method)
}
}
sort.Strings(methods)
for _, name := range methods {
fmt.Fprintln(c.w, name)
}
return nil
}
func (c *CLI) ListServices(_ context.Context) error {
services := make(map[string]struct{})
for name := range clientMethods {
service, _ := parseKey(name)
services[service] = struct{}{}
}
names := make([]string, 0)
for name := range services {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Fprintln(c.w, name)
}
return nil
}
func parseKey(key string) (string, string) {
parts := strings.Split(key, "#")
service := parts[0]
method := strings.SplitN(parts[1], ".", 2)[1]
return service, method
}
func buildKey(service, method string) string {
return fmt.Sprintf("%s#Client.%s", service, method)
}
func kebabToCamel(kebab string) string {
parts := strings.Split(kebab, "-")
results := make([]string, 0, len(parts))
for _, p := range parts {
if len(p) == 0 {
continue
}
results = append(results, strings.ToUpper(p[:1])+p[1:])
}
return strings.Join(results, "")
}
//go:generate go run cmd/aws-sdk-client-gen/main.go cmd/aws-sdk-client-gen/gen.go