forked from railwayapp/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprompt.go
308 lines (263 loc) · 7.95 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
package ui
import (
"errors"
"fmt"
"reflect"
"sort"
"strings"
"github.com/manifoldco/promptui"
"github.com/railwayapp/cli/entity"
)
type Prompt string
type Selection string
const (
InitNew Selection = "Empty Project"
InitFromTemplate Selection = "Starter Template"
)
func PromptInit() (Selection, error) {
_, selection, err := selectString("Starting Point", []string{string(InitNew), string(InitFromTemplate)})
return Selection(selection), err
}
func PromptText(text string) (string, error) {
prompt := promptui.Prompt{
Label: text,
}
return prompt.Run()
}
func hasTeams(projects []*entity.Project) bool {
teamKeys := make(map[string]bool)
teams := make([]string, 0)
for _, project := range projects {
if project.Team != nil {
if _, value := teamKeys[*project.Team]; !value {
teamKeys[*project.Team] = true
teams = append(teams, *project.Team)
}
}
}
return len(teams) > 1
}
func promptTeams(projects []*entity.Project) (*string, error) {
if hasTeams(projects) {
teams := make([]string, 0)
teamCheck := make(map[string]bool)
for _, project := range projects {
if project.Team == nil {
continue
}
// Ensure teams are only appended once by checking teamCheck
if _, hasSeenTeam := teamCheck[*project.Team]; !hasSeenTeam {
teams = append(teams, *project.Team)
teamCheck[*project.Team] = true
}
}
_, team, err := selectString("Team", teams)
return &team, err
}
return nil, nil
}
func PromptProjects(projects []*entity.Project) (*entity.Project, error) {
// Check if need to prompt teams
team, err := promptTeams(projects)
if err != nil {
return nil, err
}
filteredProjects := make([]*entity.Project, 0)
if team == nil {
filteredProjects = projects
} else {
for _, project := range projects {
if *project.Team == *team {
filteredProjects = append(filteredProjects, project)
}
}
}
sort.Slice(filteredProjects, func(i int, j int) bool {
return filteredProjects[i].UpdatedAt > filteredProjects[j].UpdatedAt
})
i, _, err := selectCustom("Project", filteredProjects, func(index int) string {
return filteredProjects[index].Name
})
return filteredProjects[i], err
}
// PromptStarterTemplates prompts the user to select one of the provided starter templates
func PromptStarterTemplates(starters []*entity.Starter) (*entity.Starter, error) {
i, _, err := selectCustom("Starter", starters, func(index int) string {
return starters[index].Title
})
return starters[i], err
}
func PromptIsRepoPrivate() (bool, error) {
_, visibility, err := selectString("Visibility", []string{"Public", "Private"})
return visibility == "Private", err
}
func PromptEnvVars(envVars []*entity.StarterEnvVar) (map[string]string, error) {
variables := make(map[string]string)
if len(envVars) > 0 {
fmt.Printf("\n%s\n", Bold("Environment Variables"))
}
for _, envVar := range envVars {
prompt := promptui.Prompt{
Label: envVar.Name,
Default: envVar.Default,
}
if envVar.Optional {
fmt.Printf("\n%s %s\n", envVar.Desc, GrayText("(Optional)"))
} else {
fmt.Printf("\n%s %s\n", envVar.Desc, GrayText("(Required)"))
prompt.Validate = validatorRequired("value required")
}
v, err := prompt.Run()
if err != nil {
return nil, err
}
variables[envVar.Name] = v
}
// Extra newline to match the ones outputted in the loop
fmt.Print("\n")
return variables, nil
}
func PromptProjectName() (string, error) {
prompt := promptui.Prompt{
Label: "Enter project name",
Templates: &promptui.PromptTemplates{
Prompt: "{{ . }} ",
Valid: fmt.Sprintf("%s {{ . | bold }}: ", promptui.IconGood),
Invalid: fmt.Sprintf("%s {{ . | bold }}: ", promptui.IconBad),
Success: fmt.Sprintf("%s {{ . | magenta | bold }}: ", promptui.IconGood),
},
Validate: validatorRequired("project name required"),
}
return prompt.Run()
}
func PromptConfirmProjectName() (string, error) {
prompt := promptui.Prompt{
Label: "Confirm project name",
Templates: &promptui.PromptTemplates{
Prompt: "{{ . }} ",
Valid: fmt.Sprintf("%s {{ . | bold }}: ", promptui.IconGood),
Invalid: fmt.Sprintf("%s {{ . | bold }}: ", promptui.IconBad),
Success: fmt.Sprintf("%s {{ . | magenta | bold }}: ", promptui.IconGood),
},
}
return prompt.Run()
}
// PromptGitHubScopes prompts the user to select one of the provides scopes
func PromptGitHubScopes(scopes []string) (string, error) {
if len(scopes) == 1 {
return scopes[0], nil
}
_, scope, err := selectString("GitHub Owner", scopes)
return scope, err
}
func PromptEnvironments(environments []*entity.Environment) (*entity.Environment, error) {
if len(environments) == 1 {
environment := environments[0]
fmt.Printf("%s Environment: %s\n", promptui.IconGood, BlueText(environment.Name))
return environment, nil
}
i, _, err := selectCustom("Environment", environments, func(index int) string {
return environments[index].Name
})
if err != nil {
return nil, err
}
return environments[i], nil
}
func PromptServices(services []*entity.Service) (*entity.Service, error) {
if len(services) == 0 {
return &entity.Service{}, nil
}
if len(services) == 1 {
return services[0], nil
}
i, _, err := selectCustom("Service", services, func(index int) string {
return services[index].Name
})
if err != nil {
return nil, err
}
return services[i], nil
}
func PromptPlugins(plugins []string) (string, error) {
i, _, err := selectString("Plugin", plugins)
return plugins[i], err
}
// PromptYesNo prompts the user to continue an action using the common (y/N) action
func PromptYesNo(msg string) (bool, error) {
fmt.Printf("%s (y/N): ", msg)
var response string
_, err := fmt.Scan(&response)
if err != nil {
return false, err
}
response = strings.ToLower(response)
isNo := response == "n" || response == "no"
isYes := response == "y" || response == "yes"
if isYes {
return true, nil
} else if isNo {
return false, nil
} else {
fmt.Println("Please type yes or no and then press enter:")
return PromptYesNo(msg)
}
}
func validatorRequired(errorMsg string) func(s string) error {
return func(s string) error {
if strings.TrimSpace(s) == "" {
return errors.New(errorMsg)
}
return nil
}
}
// selectWrapper wraps an arbitrary stringify function + associated index, used by the select
// helpers so it can accept an arbitrary slice. It also implements the Stringer interface so
// it can automatically be printed by %s
type selectItemWrapper struct {
stringify func(index int) string
index int
}
// String adheres to the Stringer interface and returns the string representation from the
// stringify function
func (w selectItemWrapper) String() string {
return w.stringify(w.index)
}
// selectString prompts the user to select a string from the provided slice
func selectString(label string, items []string) (int, string, error) {
return selectCustom(label, items, func(index int) string {
return fmt.Sprintf("%v", items[index])
})
}
// selectCustom prompts the user to select an item from the provided slice. A stringify function is passed, which
// is responsible for returning a label for the item, when called.
func selectCustom(label string, items interface{}, stringify func(index int) string) (int, string, error) {
v := reflect.ValueOf(items)
if v.Kind() != reflect.Slice {
panic(fmt.Errorf("forEachValue: expected slice type, found %q", v.Kind().String()))
}
wrappedItems := make([]selectItemWrapper, 0)
for i := 0; i < v.Len(); i++ {
wrappedItems = append(wrappedItems, selectItemWrapper{
stringify: stringify,
index: i,
})
}
options := &promptui.Select{
Label: fmt.Sprintf("Select %s", label),
Items: wrappedItems,
Size: 10,
Templates: &promptui.SelectTemplates{
Active: fmt.Sprintf(`%s {{ . | underline }}`, promptui.IconSelect),
Inactive: ` {{ . }}`,
Selected: fmt.Sprintf("%s %s: {{ . | magenta | bold }} ", promptui.IconGood, label),
},
Searcher: func(input string, i int) bool {
return strings.Contains(
strings.ToLower(stringify(i)),
strings.ToLower(input),
)
},
}
return options.Run()
}