-
Notifications
You must be signed in to change notification settings - Fork 928
/
ui.go
313 lines (264 loc) · 7.36 KB
/
ui.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
package terminal
import (
"fmt"
"io"
"strings"
. "code.cloudfoundry.org/cli/cf/i18n"
"bytes"
"bufio"
"code.cloudfoundry.org/cli/cf"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/trace"
)
type ColoringFunction func(value string, row int, col int) string
func NotLoggedInText() string {
return fmt.Sprintf(T("Not logged in. Use '{{.CFLoginCommand}}' or '{{.CFLoginCommandSSO}}' to log in.", map[string]interface{}{"CFLoginCommand": CommandColor(cf.Name + " " + "login"),
"CFLoginCommandSSO": CommandColor(cf.Name + " " + "login --sso")}))
}
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . UI
type UI interface {
PrintPaginator(rows []string, err error)
Say(message string, args ...interface{})
// ProgressReader
PrintCapturingNoOutput(message string, args ...interface{})
Warn(message string, args ...interface{})
Ask(prompt string) (answer string)
AskForPassword(prompt string) (answer string)
Confirm(message string) bool
ConfirmDelete(modelType, modelName string) bool
ConfirmDeleteWithAssociations(modelType, modelName string) bool
Ok()
Failed(message string, args ...interface{})
ShowConfiguration(coreconfig.Reader) error
LoadingIndication()
Table(headers []string) *UITable
NotifyUpdateIfNeeded(coreconfig.Reader)
Writer() io.Writer
}
type Printer interface {
Print(a ...interface{}) (n int, err error)
Printf(format string, a ...interface{}) (n int, err error)
Println(a ...interface{}) (n int, err error)
}
type terminalUI struct {
stdin io.Reader
stdout io.Writer
printer Printer
logger trace.Printer
scanner *bufio.Scanner
}
func NewUI(r io.Reader, w io.Writer, printer Printer, logger trace.Printer) UI {
return &terminalUI{
stdin: r,
stdout: w,
printer: printer,
logger: logger,
scanner: bufio.NewScanner(r),
}
}
func (ui terminalUI) Writer() io.Writer {
return ui.stdout
}
func (ui *terminalUI) PrintPaginator(rows []string, err error) {
if err != nil {
ui.Failed(err.Error())
return
}
for _, row := range rows {
ui.Say(row)
}
}
func (ui *terminalUI) PrintCapturingNoOutput(message string, args ...interface{}) {
if len(args) == 0 {
fmt.Fprintf(ui.stdout, "%s", message)
} else {
fmt.Fprintf(ui.stdout, message, args...)
}
}
func (ui *terminalUI) Say(message string, args ...interface{}) {
if len(args) == 0 {
_, _ = ui.printer.Printf("%s\n", message)
} else {
_, _ = ui.printer.Printf(message+"\n", args...)
}
}
func (ui *terminalUI) Warn(message string, args ...interface{}) {
message = fmt.Sprintf(message, args...)
ui.Say(WarningColor(message))
return
}
func (ui *terminalUI) Ask(prompt string) string {
fmt.Fprintf(ui.stdout, "\n%s%s ", prompt, PromptColor(">"))
if ui.scanner.Scan() {
w := ui.scanner.Text()
return strings.TrimSpace(w)
}
return ""
}
func (ui *terminalUI) ConfirmDeleteWithAssociations(modelType, modelName string) bool {
return ui.confirmDelete(T("Really delete the {{.ModelType}} {{.ModelName}} and everything associated with it?",
map[string]interface{}{
"ModelType": modelType,
"ModelName": EntityNameColor(modelName),
}))
}
func (ui *terminalUI) ConfirmDelete(modelType, modelName string) bool {
return ui.confirmDelete(T("Really delete the {{.ModelType}} {{.ModelName}}?",
map[string]interface{}{
"ModelType": modelType,
"ModelName": EntityNameColor(modelName),
}))
}
func (ui *terminalUI) confirmDelete(message string) bool {
result := ui.Confirm(message)
if !result {
ui.Warn(T("Delete cancelled"))
}
return result
}
func (ui *terminalUI) Confirm(message string) bool {
response := ui.Ask(message)
switch strings.ToLower(response) {
case "y", "yes", T("yes"):
return true
}
return false
}
func (ui *terminalUI) Ok() {
ui.Say(SuccessColor(T("OK")))
}
func (ui *terminalUI) Failed(message string, args ...interface{}) {
message = fmt.Sprintf(message, args...)
failed := "FAILED"
if T != nil {
failed = T("FAILED")
}
ui.logger.Print(failed)
ui.logger.Print(message)
if !ui.logger.WritesToConsole() {
ui.Say(FailureColor(failed))
ui.Say(message)
}
}
func (ui *terminalUI) ShowConfiguration(config coreconfig.Reader) error {
var err error
table := ui.Table([]string{"", ""})
if config.HasAPIEndpoint() {
table.Add(
T("API endpoint:"),
T("{{.APIEndpoint}} (API version: {{.APIVersionString}})",
map[string]interface{}{
"APIEndpoint": EntityNameColor(config.APIEndpoint()),
"APIVersionString": EntityNameColor(config.APIVersion()),
}),
)
}
if !config.IsLoggedIn() {
err = table.Print()
if err != nil {
return err
}
ui.Say(NotLoggedInText())
return nil
}
table.Add(T("User:"), EntityNameColor(config.UserEmail()))
if !config.HasOrganization() && !config.HasSpace() {
err = table.Print()
if err != nil {
return err
}
command := fmt.Sprintf("%s target -o ORG -s SPACE", cf.Name)
ui.Say(T("No org or space targeted, use '{{.CFTargetCommand}}'",
map[string]interface{}{
"CFTargetCommand": CommandColor(command),
}))
return nil
}
if config.HasOrganization() {
table.Add(
T("Org:"),
EntityNameColor(config.OrganizationFields().Name),
)
} else {
command := fmt.Sprintf("%s target -o Org", cf.Name)
table.Add(
T("Org:"),
T("No org targeted, use '{{.CFTargetCommand}}'",
map[string]interface{}{
"CFTargetCommand": CommandColor(command),
}),
)
}
if config.HasSpace() {
table.Add(
T("Space:"),
EntityNameColor(config.SpaceFields().Name),
)
} else {
command := fmt.Sprintf("%s target -s SPACE", cf.Name)
table.Add(
T("Space:"),
T("No space targeted, use '{{.CFTargetCommand}}'", map[string]interface{}{"CFTargetCommand": CommandColor(command)}),
)
}
err = table.Print()
if err != nil {
return err
}
return nil
}
func (ui *terminalUI) LoadingIndication() {
_, _ = ui.printer.Print(".")
}
func (ui *terminalUI) Table(headers []string) *UITable {
return &UITable{
UI: ui,
Table: NewTable(headers),
}
}
type UITable struct {
UI UI
Table *Table
}
func (u *UITable) Add(row ...string) {
u.Table.Add(row...)
}
// Print formats the table and then prints it to the UI specified at
// the time of the construction. Afterwards the table is cleared,
// becoming ready for another round of rows and printing.
func (u *UITable) Print() error {
result := &bytes.Buffer{}
t := u.Table
err := t.PrintTo(result)
if err != nil {
return err
}
// DevNote. With the change to printing into a buffer all
// lines now come with a terminating \n. The t.ui.Say() below
// will then add another \n to that. To avoid this additional
// line we chop off the last \n from the output (if there is
// any). Operating on the slice avoids string copying.
//
// WIBNI if the terminal API had a variant of Say not assuming
// that each output is a single line.
r := result.Bytes()
if len(r) > 0 {
r = r[0 : len(r)-1]
}
// Only generate output for a non-empty table.
if len(r) > 0 {
u.UI.Say("%s", string(r))
}
return nil
}
func (ui *terminalUI) NotifyUpdateIfNeeded(config coreconfig.Reader) {
if !config.IsMinCLIVersion(config.CLIVersion()) {
ui.Say("")
ui.Say(T("Cloud Foundry API version {{.APIVer}} requires CLI version {{.CLIMin}}. You are currently on version {{.CLIVer}}. To upgrade your CLI, please visit: https://github.com/cloudfoundry/cli#downloads",
map[string]interface{}{
"APIVer": config.APIVersion(),
"CLIMin": config.MinCLIVersion(),
"CLIVer": config.CLIVersion(),
}))
}
}