-
Notifications
You must be signed in to change notification settings - Fork 1
/
gateway.go
365 lines (305 loc) · 8.57 KB
/
gateway.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"regexp"
"github.com/MakeNowJust/heredoc/v2"
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/fatih/color"
"github.com/rodaine/table"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/bcgov/gwa-cli/pkg"
)
func NewGatewayCmd(ctx *pkg.AppContext) *cobra.Command {
gatewayCmd := &cobra.Command{
Use: "gateway",
Short: "Manage your gateways",
Long: `Gateways are used to organize your services.`,
}
gatewayCmd.AddCommand(GatewayListCmd(ctx))
gatewayCmd.AddCommand(GatewayCreateCmd(ctx))
gatewayCmd.AddCommand(GatewayDestroyCmd(ctx))
gatewayCmd.AddCommand(GatewayCurrentCmd(ctx))
return gatewayCmd
}
type GatewayFormData struct {
GatewayId string `json:"gatewayId,omitempty" url:"gatewayId,omitempty"`
DisplayName string `json:"displayName,omitempty" url:"displayName,omitempty"`
}
func (n *GatewayFormData) IsEmpty() bool {
return n.DisplayName == "" && n.GatewayId == ""
}
func GatewayListCmd(ctx *pkg.AppContext) *cobra.Command {
listCommand := &cobra.Command{
Use: "list",
Short: "List all your managed gateways",
RunE: pkg.WrapError(ctx, func(_ *cobra.Command, _ []string) error {
path := "/ds/api/v3/gateways"
URL, _ := ctx.CreateUrl(path, nil)
r, err := pkg.NewApiGet[[]GatewayFormData](ctx, URL)
if err != nil {
return err
}
loader := pkg.NewSpinner()
loader.Start()
response, err := r.Do()
if err != nil {
loader.Stop()
if response.StatusCode == http.StatusUnauthorized {
fmt.Println()
fmt.Println(
heredoc.Doc(`
Next Steps:
Run gwa login to obtain another auth token
`),
)
}
return err
}
loader.Stop()
if len(response.Data) <= 0 {
fmt.Println("You have no gateways")
}
if len(response.Data) > 0 {
headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
columnFmt := color.New(color.FgYellow).SprintfFunc()
tbl := table.New("Display Name", "Gateway ID")
tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt)
for _, n := range response.Data {
tbl.AddRow(n.DisplayName, n.GatewayId)
}
tbl.Print()
}
return nil
}),
}
return listCommand
}
// Start Prompt Code
type statusMsg int
func runCreateRequest(m pkg.GenerateModel) tea.Cmd {
return func() tea.Msg {
data := &GatewayFormData{}
data.DisplayName = m.Prompts[displayName].TextInput.Value()
gw, err := createGateway(m.Ctx, data)
if err != nil {
return pkg.PromptOutputErr{Err: err}
}
fmt.Println(gw)
err = setCurrentGateway(gw)
if err != nil {
return pkg.PromptOutputErr{Err: err}
}
return pkg.PromptCompleteEvent(gw)
}
}
const (
displayName = iota
)
func initialModel(ctx *pkg.AppContext) pkg.GenerateModel {
var prompts = make([]pkg.PromptField, 1)
prompts[displayName] = pkg.NewTextInput("Display name", "A short, human-readable name", false)
prompts[displayName].TextInput.Focus()
s := spinner.New()
s.Spinner = spinner.Dot
m := pkg.GenerateModel{
Action: runCreateRequest,
Ctx: ctx,
Header: heredoc.Doc(`
Create Gateway
Hit enter to accept the default display name (<IDIR>'s gateway) or provide a name below.
Display names may consist of:
- Letters, numbers, spaces or the special characters -()_/.'
- 3-30 characters
`),
Prompts: prompts,
Spinner: s,
}
return m
}
func GatewayCreateCmd(ctx *pkg.AppContext) *cobra.Command {
generate := false
var gatewayFormData GatewayFormData
createCommand := &cobra.Command{
Use: "create",
Short: "Create a new gateway",
Example: heredoc.Doc(`
$ gwa gateway create --generate
$ gwa gateway create --gateway-id my-gateway --display-name="This is my gateway"
`),
RunE: pkg.WrapError(ctx, func(_ *cobra.Command, _ []string) error {
if gatewayFormData.IsEmpty() && generate == false {
model := initialModel(ctx)
if _, err := tea.NewProgram(model).Run(); err != nil {
return err
}
return nil
}
gateway, err := createGateway(ctx, &gatewayFormData)
if err != nil {
return err
}
pkg.Info("Setting gateway to " + gateway)
err = setCurrentGateway(gateway)
if err != nil {
return err
}
return nil
}),
}
createCommand.Flags().
BoolVarP(&generate, "generate", "g", false, "generates a unique gateway with the default display name")
createCommand.Flags().
StringVarP(&gatewayFormData.GatewayId, "gateway-id", "i", "", "optionally specify the gateway ID")
createCommand.Flags().
StringVarP(&gatewayFormData.DisplayName, "display-name", "d", "", "optionally set the gateway display name")
return createCommand
}
type GatewayResult struct {
GatewayId string `json:"gatewayId,omitempty"`
DisplayName string `json:"displayName,omitempty"`
}
func createGateway(ctx *pkg.AppContext, data *GatewayFormData) (string, error) {
path := fmt.Sprintf("/ds/api/%s/gateways", ctx.ApiVersion)
URL, err := ctx.CreateUrl(path, nil)
if err != nil {
return "", err
}
body, err := json.Marshal(data)
if err != nil {
return "", err
}
r, err := pkg.NewApiPost[GatewayResult](ctx, URL, bytes.NewBuffer(body))
if err != nil {
return "", err
}
response, err := r.Do()
if err != nil {
return "", err
}
if response.Data.DisplayName != "" {
fmt.Printf("Gateway created. Gateway ID: %s, display name: %s\n", response.Data.GatewayId, response.Data.DisplayName)
} else {
fmt.Printf("Gateway created. Gateway ID: %s\n", response.Data.GatewayId)
}
return response.Data.GatewayId, nil
}
func GatewayCurrentCmd(ctx *pkg.AppContext) *cobra.Command {
currentCmd := &cobra.Command{
Use: "current",
Short: "Display the current gateway",
RunE: func(_ *cobra.Command, _ []string) error {
if ctx.Gateway == "" {
fmt.Println(heredoc.Doc(`
You can create a gateway by running:
$ gwa gateway create
`))
return fmt.Errorf("no gateway has been defined")
}
path := fmt.Sprintf("/ds/api/v3/gateways/%s", ctx.Gateway)
URL, _ := ctx.CreateUrl(path, nil)
r, err := pkg.NewApiGet[GatewayFormData](ctx, URL)
if err != nil {
return err
}
loader := pkg.NewSpinner()
loader.Start()
response, err := r.Do()
if err != nil {
loader.Stop()
if response.StatusCode == http.StatusUnauthorized {
fmt.Println()
fmt.Println(
heredoc.Doc(`
Next Steps:
Run gwa login to obtain another auth token
`),
)
}
return err
}
loader.Stop()
headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc()
columnFmt := color.New(color.FgYellow).SprintfFunc()
tbl := table.New("Display Name", "Gateway ID")
tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt)
tbl.AddRow(response.Data.DisplayName, ctx.Gateway)
tbl.Print()
return nil
},
}
return currentCmd
}
func setCurrentGateway(gw string) error {
viper.Set("gateway", gw)
err := viper.WriteConfig()
if err != nil {
return err
}
return nil
}
type GatewayDestroyOptions struct {
Force bool `url:"force"`
}
func GatewayDestroyCmd(ctx *pkg.AppContext) *cobra.Command {
var destroyOptions GatewayDestroyOptions
destroyCommand := &cobra.Command{
Use: "destroy",
Short: "Destroy the current gateway",
RunE: pkg.WrapError(ctx, func(_ *cobra.Command, _ []string) error {
if ctx.Gateway == "" {
fmt.Println(heredoc.Doc(`
A gateway must be set via the config command
Example:
$ gwa config set gateway YOUR_GATEWAY_NAME
`),
)
return fmt.Errorf("No gateway has been set")
}
loader := pkg.NewSpinner()
loader.Start()
err := destroyGateway(ctx, &destroyOptions)
loader.Stop()
if err != nil {
return err
}
err = setCurrentGateway("")
if err != nil {
return err
}
fmt.Println("Gateway destroyed:", ctx.Gateway)
return nil
}),
}
destroyCommand.Flags().BoolVar(&destroyOptions.Force, "force", false, "force deletion")
return destroyCommand
}
func destroyGateway(ctx *pkg.AppContext, destroyOptions *GatewayDestroyOptions) error {
pathname := fmt.Sprintf("/ds/api/%s/gateways/%s", ctx.ApiVersion, ctx.Gateway)
URL, err := ctx.CreateUrl(pathname, destroyOptions)
if err != nil {
return err
}
r, err := pkg.NewApiDelete[GatewayResult](ctx, URL)
if err != nil {
return err
}
_, err = r.Do()
if err != nil {
return err
}
return nil
}
func validateGateway(input string) error {
pattern := `^[a-zA-Z0-9\-]{3,15}$`
r := regexp.MustCompile(pattern)
if !r.MatchString(input) {
err := fmt.Errorf("%s is an invalid gateway", pkg.BoldStyle.Copy().Underline(true).Render(input))
return pkg.PromptValidationErr{Err: err}
}
return nil
}