-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathclient_cli.go
319 lines (294 loc) Β· 9.15 KB
/
client_cli.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package codegen
import (
"fmt"
"path/filepath"
"goa.design/goa/codegen"
"goa.design/goa/codegen/cli"
"goa.design/goa/expr"
)
// commandData wraps the common CommandData and adds HTTP-specific fields.
type commandData struct {
*cli.CommandData
// Subcommands is the list of endpoint commands.
Subcommands []*subcommandData
// NeedStream if true initializes the websocket dialer.
NeedStream bool
}
// commandData wraps the common SubcommandData and adds HTTP-specific fields.
type subcommandData struct {
*cli.SubcommandData
// MultipartFuncName is the function name used to render a multipart request encoder.
MultipartFuncName string
// MultipartFuncName is the variable name used to render a multipart request encoder.
MultipartVarName string
}
// ClientCLIFiles returns the client HTTP CLI support file.
func ClientCLIFiles(genpkg string, root *expr.RootExpr) []*codegen.File {
if len(root.API.HTTP.Services) == 0 {
return nil
}
var (
data []*commandData
svcs []*expr.HTTPServiceExpr
)
for _, svc := range root.API.HTTP.Services {
sd := HTTPServices.Get(svc.Name())
if len(sd.Endpoints) > 0 {
command := &commandData{
CommandData: cli.BuildCommandData(sd.Service),
NeedStream: hasStreaming(sd),
}
for _, e := range sd.Endpoints {
sub := buildSubcommandData(sd, e)
command.Subcommands = append(command.Subcommands, sub)
command.CommandData.Subcommands = append(command.CommandData.Subcommands, sub.SubcommandData)
}
command.Example = command.Subcommands[0].Example
data = append(data, command)
svcs = append(svcs, svc)
}
}
var files []*codegen.File
for _, svr := range root.API.Servers {
files = append(files, endpointParser(genpkg, root, svr, data))
}
for i, svc := range svcs {
files = append(files, payloadBuilders(genpkg, svc, data[i].CommandData))
}
return files
}
func buildSubcommandData(sd *ServiceData, e *EndpointData) *subcommandData {
flags, buildFunction := buildFlags(sd, e)
sub := &subcommandData{
SubcommandData: cli.BuildSubcommandData(sd.Service.Name, e.Method, buildFunction, flags),
}
if e.MultipartRequestEncoder != nil {
sub.MultipartVarName = e.MultipartRequestEncoder.VarName
sub.MultipartFuncName = e.MultipartRequestEncoder.FuncName
}
return sub
}
// endpointParser returns the file that implements the command line parser that
// builds the client endpoint and payload necessary to perform a request.
func endpointParser(genpkg string, root *expr.RootExpr, svr *expr.ServerExpr, data []*commandData) *codegen.File {
pkg := codegen.SnakeCase(codegen.Goify(svr.Name, true))
path := filepath.Join(codegen.Gendir, "http", "cli", pkg, "cli.go")
title := fmt.Sprintf("%s HTTP client CLI support package", svr.Name)
specs := []*codegen.ImportSpec{
{Path: "encoding/json"},
{Path: "flag"},
{Path: "fmt"},
{Path: "net/http"},
{Path: "os"},
{Path: "strconv"},
{Path: "unicode/utf8"},
{Path: "goa.design/goa", Name: "goa"},
{Path: "goa.design/goa/http", Name: "goahttp"},
}
for _, sv := range svr.Services {
svc := root.Service(sv)
sd := HTTPServices.Get(svc.Name)
if sd == nil {
continue
}
specs = append(specs, &codegen.ImportSpec{
Path: genpkg + "/http/" + codegen.SnakeCase(sd.Service.VarName) + "/client",
Name: sd.Service.PkgName + "c",
})
}
cliData := make([]*cli.CommandData, len(data))
for i, cmd := range data {
cliData[i] = cmd.CommandData
}
sections := []*codegen.SectionTemplate{
codegen.Header(title, "cli", specs),
cli.UsageCommands(cliData),
cli.UsageExamples(cliData),
{
Name: "parse-endpoint",
Source: parseEndpointT,
Data: struct {
FlagsCode string
Commands []*commandData
}{
cli.FlagsCode(cliData),
data,
},
FuncMap: map[string]interface{}{
"streamingCmdExists": streamingCmdExists,
},
},
}
for _, cmd := range cliData {
sections = append(sections, cli.CommandUsage(cmd))
}
return &codegen.File{Path: path, SectionTemplates: sections}
}
// payloadBuilders returns the file that contains the payload constructors that
// use flag values as arguments.
func payloadBuilders(genpkg string, svc *expr.HTTPServiceExpr, data *cli.CommandData) *codegen.File {
sd := HTTPServices.Get(svc.Name())
path := filepath.Join(codegen.Gendir, "http", codegen.SnakeCase(sd.Service.VarName), "client", "cli.go")
title := fmt.Sprintf("%s HTTP client CLI support package", svc.Name())
specs := []*codegen.ImportSpec{
{Path: "encoding/json"},
{Path: "fmt"},
{Path: "net/http"},
{Path: "os"},
{Path: "strconv"},
{Path: "unicode/utf8"},
{Path: "goa.design/goa", Name: "goa"},
{Path: "goa.design/goa/http", Name: "goahttp"},
{Path: genpkg + "/" + codegen.SnakeCase(sd.Service.VarName), Name: sd.Service.PkgName},
}
sections := []*codegen.SectionTemplate{
codegen.Header(title, "client", specs),
}
for _, sub := range data.Subcommands {
if sub.BuildFunction != nil {
sections = append(sections, cli.PayloadBuilderSection(sub.BuildFunction))
}
}
return &codegen.File{Path: path, SectionTemplates: sections}
}
func buildFlags(svc *ServiceData, e *EndpointData) ([]*cli.FlagData, *cli.BuildFunctionData) {
var (
flags []*cli.FlagData
buildFunction *cli.BuildFunctionData
)
svcn := svc.Service.Name
en := e.Method.Name
if e.Payload != nil {
if e.Payload.Request.PayloadInit != nil {
args := e.Payload.Request.PayloadInit.ClientArgs
args = append(args, e.Payload.Request.PayloadInit.CLIArgs...)
flags, buildFunction = makeFlags(e, args)
} else if e.Payload.Ref != "" {
flags = append(flags, cli.NewFlagData(svcn, en, "p", e.Method.PayloadRef, e.Method.PayloadDesc, true, e.Method.PayloadEx))
}
}
return flags, buildFunction
}
func makeFlags(e *EndpointData, args []*InitArgData) ([]*cli.FlagData, *cli.BuildFunctionData) {
var (
fdata []*cli.FieldData
flags = make([]*cli.FlagData, len(args))
params = make([]string, len(args))
pInitArgs = make([]*cli.PayloadInitArgData, len(args))
check bool
)
for i, arg := range args {
pInitArgs[i] = &cli.PayloadInitArgData{
Name: arg.Name,
Pointer: arg.Pointer,
FieldName: arg.FieldName,
FieldPointer: arg.FieldPointer,
}
f := cli.NewFlagData(e.ServiceName, e.Method.Name, arg.Name, arg.TypeName, arg.Description, arg.Required, arg.Example)
flags[i] = f
params[i] = f.FullName
if arg.FieldName == "" && arg.Name != "body" {
continue
}
code, chek := cli.FieldLoadCode(f, arg.Name, arg.TypeName, arg.Validate, arg.DefaultValue)
check = check || chek
tn := arg.TypeRef
if f.Type == "JSON" {
// We need to declare the variable without
// a pointer to be able to unmarshal the JSON
// using its address.
tn = arg.TypeName
}
fdata = append(fdata, &cli.FieldData{
Name: arg.Name,
VarName: arg.Name,
TypeRef: tn,
Init: code,
})
}
pInit := cli.PayloadInitData{
Code: e.Payload.Request.PayloadInit.ClientCode,
ReturnTypeAttribute: e.Payload.Request.PayloadInit.ReturnTypeAttribute,
ReturnIsStruct: e.Payload.Request.PayloadInit.ReturnIsStruct,
ReturnTypeName: e.Payload.Request.PayloadInit.ReturnTypeName,
Args: pInitArgs,
}
return flags, &cli.BuildFunctionData{
Name: "Build" + e.Method.VarName + "Payload",
ActualParams: params,
FormalParams: params,
ServiceName: e.ServiceName,
MethodName: e.Method.Name,
ResultType: e.Payload.Ref,
Fields: fdata,
PayloadInit: &pInit,
CheckErr: check,
}
}
// streamingCmdExists returns true if at least one command in the list of commands
// uses stream for sending payload/result.
func streamingCmdExists(data []*commandData) bool {
for _, c := range data {
if c.NeedStream {
return true
}
}
return false
}
const parseEndpointT = `// ParseEndpoint returns the endpoint and payload as specified on the command
// line.
func ParseEndpoint(
scheme, host string,
doer goahttp.Doer,
enc func(*http.Request) goahttp.Encoder,
dec func(*http.Response) goahttp.Decoder,
restore bool,
{{- if streamingCmdExists .Commands }}
dialer goahttp.Dialer,
{{- range .Commands }}
{{- if .NeedStream }}
{{ .VarName }}Configurer *{{ .PkgName }}.ConnConfigurer,
{{- end }}
{{- end }}
{{- end }}
{{- range $c := .Commands }}
{{- range .Subcommands }}
{{- if .MultipartVarName }}
{{ .MultipartVarName }} {{ $c.PkgName }}.{{ .MultipartFuncName }},
{{- end }}
{{- end }}
{{- end }}
) (goa.Endpoint, interface{}, error) {
{{ .FlagsCode }}
var (
data interface{}
endpoint goa.Endpoint
err error
)
{
switch svcn {
{{- range .Commands }}
case "{{ .Name }}":
c := {{ .PkgName }}.NewClient(scheme, host, doer, enc, dec, restore{{ if .NeedStream }}, dialer, {{ .VarName }}Configurer{{ end }})
switch epn {
{{- $pkgName := .PkgName }}{{ range .Subcommands }}
case "{{ .Name }}":
endpoint = c.{{ .MethodVarName }}({{ if .MultipartVarName }}{{ .MultipartVarName }}{{ end }})
{{- if .BuildFunction }}
data, err = {{ $pkgName}}.{{ .BuildFunction.Name }}({{ range .BuildFunction.ActualParams }}*{{ . }}Flag, {{ end }})
{{- else if .Conversion }}
{{ .Conversion }}
{{- else }}
data = nil
{{- end }}
{{- end }}
}
{{- end }}
}
}
if err != nil {
return nil, nil, err
}
return endpoint, data, nil
}
`