-
Notifications
You must be signed in to change notification settings - Fork 224
/
prompt.go
420 lines (337 loc) · 9.63 KB
/
prompt.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Package prompt implements input-related functionality.
package prompt
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/samber/lo"
"github.com/superfly/flyctl/iostreams"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/internal/config"
"github.com/superfly/flyctl/internal/sort"
)
type RegionParams struct {
Message string
ExcludedRegionCodes []string
}
func String(ctx context.Context, dst *string, msg, def string, required bool) error {
opt, err := newSurveyIO(ctx)
if err != nil {
return err
}
p := &survey.Input{
Message: msg,
Default: def,
}
opts := []survey.AskOpt{opt}
if required {
opts = append(opts, survey.WithValidator(survey.Required))
}
return survey.AskOne(p, dst, opts...)
}
func Int(ctx context.Context, dst *int, msg string, def int, required bool) error {
opt, err := newSurveyIO(ctx)
if err != nil {
return err
}
p := &survey.Input{
Message: msg,
Default: strconv.Itoa(def),
}
opts := []survey.AskOpt{opt}
if required {
opts = append(opts, survey.WithValidator(survey.Required))
}
// add a validator to ensure that the input is an integer
opts = append(opts, survey.WithValidator(func(val interface{}) error {
_, err := strconv.Atoi(val.(string))
if err != nil {
return errors.New("must be an integer")
}
return nil
}))
return survey.AskOne(p, dst, opts...)
}
func Password(ctx context.Context, dst *string, msg string, required bool) error {
opt, err := newSurveyIO(ctx)
if err != nil {
return err
}
p := &survey.Password{
Message: msg,
}
opts := []survey.AskOpt{opt}
if required {
opts = append(opts, survey.WithValidator(survey.Required))
}
return survey.AskOne(p, dst, opts...)
}
func MultiSelect(ctx context.Context, indices *[]int, msg string, def []int, options ...string) error {
opt, err := newSurveyIO(ctx)
if err != nil {
return err
}
p := &survey.MultiSelect{
Message: msg,
Options: options,
PageSize: 15,
Default: def,
}
return survey.AskOne(p, indices, opt)
}
func Select(ctx context.Context, index *int, msg, def string, options ...string) error {
opt, err := newSurveyIO(ctx)
if err != nil {
return err
}
p := &survey.Select{
Message: msg,
Options: options,
PageSize: 15,
}
if def != "" {
p.Default = def
}
return survey.AskOne(p, index, opt)
}
func Confirmf(ctx context.Context, format string, a ...interface{}) (bool, error) {
return Confirm(ctx, fmt.Sprintf(format, a...))
}
func Confirm(ctx context.Context, message string) (confirm bool, err error) {
var opt survey.AskOpt
if opt, err = newSurveyIO(ctx); err != nil {
return
}
prompt := &survey.Confirm{
Message: message,
}
err = survey.AskOne(prompt, &confirm, opt)
return
}
func ConfirmOverwrite(ctx context.Context, filename string) (confirm bool, err error) {
prompt := &survey.Confirm{
Message: fmt.Sprintf(`Overwrite "%s"?`, filename),
}
err = survey.AskOne(prompt, &confirm)
return
}
var errNonInteractive = errors.New("prompt: non interactive")
func IsNonInteractive(err error) bool {
return errors.Is(err, errNonInteractive)
}
type NonInteractiveError string
func (e NonInteractiveError) Error() string { return string(e) }
func (NonInteractiveError) Unwrap() error { return errNonInteractive }
func newSurveyIO(ctx context.Context) (survey.AskOpt, error) {
io := iostreams.FromContext(ctx)
if !io.IsInteractive() {
return nil, errNonInteractive
}
in, ok := io.In.(terminal.FileReader)
if !ok {
return nil, errNonInteractive
}
out, ok := io.Out.(terminal.FileWriter)
if !ok {
return nil, errNonInteractive
}
return survey.WithStdio(in, out, io.ErrOut), nil
}
var errOrgSlugRequired = NonInteractiveError("org slug must be specified when not running interactively")
// Org returns the Organization the user has passed in via flag or prompts the
// user for one.
func Org(ctx context.Context) (*api.Organization, error) {
client := client.FromContext(ctx).API()
orgs, err := client.GetOrganizations(ctx)
if err != nil {
return nil, err
}
sort.OrganizationsByTypeAndName(orgs)
io := iostreams.FromContext(ctx)
slug := config.FromContext(ctx).Organization
switch {
case slug == "" && len(orgs) == 1 && orgs[0].Type == "PERSONAL":
fmt.Fprintf(io.ErrOut, "automatically selected %s organization: %s\n",
strings.ToLower(orgs[0].Type), orgs[0].Name)
return &orgs[0], nil
case slug != "":
for _, org := range orgs {
if slug == org.Slug {
return &org, nil
}
}
return nil, fmt.Errorf("organization %s not found", slug)
default:
switch org, err := SelectOrg(ctx, orgs); {
case err == nil:
return org, nil
case IsNonInteractive(err):
return nil, errOrgSlugRequired
default:
return nil, err
}
}
}
func SelectOrg(ctx context.Context, orgs []api.Organization) (org *api.Organization, err error) {
var options []string
for _, org := range orgs {
personalCallout := ""
if org.Type == "PERSONAL" && org.Slug != "personal" {
personalCallout = " [personal]"
}
options = append(options, fmt.Sprintf("%s (%s)%s", org.Name, org.Slug, personalCallout))
}
var index int
if err = Select(ctx, &index, "Select Organization:", "", options...); err == nil {
org = &orgs[index]
}
return
}
var (
errRegionCodeRequired = NonInteractiveError("region code must be specified when not running interactively")
errRegionCodesRequired = NonInteractiveError("regions codes must be specified in a comma-separated when not running interactively")
)
func sortedRegions(ctx context.Context, excludedRegionCodes []string) ([]api.Region, *api.Region, error) {
client := client.FromContext(ctx).API()
regions, defaultRegion, err := client.PlatformRegions(ctx)
if err != nil {
return nil, nil, err
}
if len(excludedRegionCodes) > 0 {
regions = lo.Filter(regions, func(r api.Region, _ int) bool {
return !lo.Contains[string](excludedRegionCodes, r.Code)
})
}
sort.RegionsByNameAndCode(regions)
return regions, defaultRegion, err
}
// Region returns the region the user has passed in via flag or prompts the
// user for one.
func MultiRegion(ctx context.Context, msg string, currentRegions []string, excludedRegionCodes []string) (*[]api.Region, error) {
regions, _, err := sortedRegions(ctx, excludedRegionCodes)
if err != nil {
return nil, err
}
switch regions, err := MultiSelectRegion(ctx, msg, regions, currentRegions); {
case err == nil:
return ®ions, nil
case IsNonInteractive(err):
return nil, errRegionCodesRequired
default:
return nil, err
}
}
// Region returns the region the user has passed in via flag or prompts the
// user for one.
func Region(ctx context.Context, params RegionParams) (*api.Region, error) {
regions, defaultRegion, err := sortedRegions(ctx, params.ExcludedRegionCodes)
if err != nil {
return nil, err
}
slug := config.FromContext(ctx).Region
switch {
case slug != "":
for _, region := range regions {
if slug == region.Code {
return ®ion, nil
}
}
return nil, fmt.Errorf("region %s not found", slug)
default:
var defaultRegionCode string
if defaultRegion != nil {
defaultRegionCode = defaultRegion.Code
}
switch region, err := SelectRegion(ctx, params.Message, regions, defaultRegionCode); {
case err == nil:
return region, nil
case IsNonInteractive(err):
return nil, errRegionCodeRequired
default:
return nil, err
}
}
}
func SelectRegion(ctx context.Context, msg string, regions []api.Region, defaultCode string) (region *api.Region, err error) {
var defaultOption string
var options []string
for _, r := range regions {
option := fmt.Sprintf("%s (%s)", r.Name, r.Code)
if r.Code == defaultCode {
defaultOption = option
}
options = append(options, option)
}
if msg == "" {
msg = "Select region:"
}
var index int
if err = Select(ctx, &index, msg, defaultOption, options...); err == nil {
region = ®ions[index]
}
return
}
func MultiSelectRegion(ctx context.Context, msg string, regions []api.Region, currentRegions []string) (selectedRegions []api.Region, err error) {
var options []string
var currentIndices []int
var indices []int
for i, r := range regions {
if lo.Contains(currentRegions, r.Code) {
currentIndices = append(currentIndices, i)
}
option := fmt.Sprintf("%s (%s)", r.Name, r.Code)
options = append(options, option)
}
if msg == "" {
msg = "Select regions:"
}
if err = MultiSelect(ctx, &indices, msg, currentIndices, options...); err == nil {
for _, index := range indices {
selectedRegions = append(selectedRegions, regions[index])
}
}
return
}
var errVMsizeRequired = NonInteractiveError("vm size must be specified when not running interactively")
func VMSize(ctx context.Context, def string) (size *api.VMSize, err error) {
client := client.FromContext(ctx).API()
vmSizes, err := client.PlatformVMSizes(ctx)
if err != nil {
return nil, err
}
sort.VMSizesBySize(vmSizes)
switch {
case def != "":
for _, vmSize := range vmSizes {
if def == vmSize.Name {
return &vmSize, nil
}
}
return nil, fmt.Errorf("vm size %s not found", def)
default:
switch vmSize, err := SelectVMSize(ctx, vmSizes); {
case err == nil:
return vmSize, nil
case IsNonInteractive(err):
return nil, errVMsizeRequired
default:
return nil, err
}
}
}
func SelectVMSize(ctx context.Context, vmSizes []api.VMSize) (vmSize *api.VMSize, err error) {
options := []string{}
for _, vmSize := range vmSizes {
options = append(options, fmt.Sprintf("%s - %d", vmSize.Name, vmSize.MemoryMB))
}
var index int
if err := Select(ctx, &index, "Select VM size:", "", options...); err != nil {
return nil, err
}
return &vmSizes[index], nil
}