forked from AlecAivazis/survey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderer.go
94 lines (77 loc) · 2.2 KB
/
renderer.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
package survey
import (
"fmt"
"strings"
"github.com/AlecAivazis/survey/v2/core"
"github.com/AlecAivazis/survey/v2/terminal"
)
type Renderer struct {
stdio terminal.Stdio
lineCount int
errorLineCount int
}
type ErrorTemplateData struct {
Error error
Icon Icon
}
var ErrorTemplate = `{{color .Icon.Format }}{{ .Icon.Text }} Sorry, your reply was invalid: {{ .Error.Error }}{{color "reset"}}
`
func (r *Renderer) WithStdio(stdio terminal.Stdio) {
r.stdio = stdio
}
func (r *Renderer) Stdio() terminal.Stdio {
return r.stdio
}
func (r *Renderer) NewRuneReader() *terminal.RuneReader {
return terminal.NewRuneReader(r.stdio)
}
func (r *Renderer) NewCursor() *terminal.Cursor {
return &terminal.Cursor{
In: r.stdio.In,
Out: r.stdio.Out,
}
}
func (r *Renderer) Error(config *PromptConfig, invalid error) error {
// since errors are printed on top we need to reset the prompt
// as well as any previous error print
r.resetPrompt(r.lineCount + r.errorLineCount)
// we just cleared the prompt lines
r.lineCount = 0
out, err := core.RunTemplate(ErrorTemplate, &ErrorTemplateData{
Error: invalid,
Icon: config.Icons.Error,
})
if err != nil {
return err
}
// keep track of how many lines are printed so we can clean up later
r.errorLineCount = strings.Count(out, "\n")
// send the message to the user
fmt.Fprint(terminal.NewAnsiStdout(r.stdio.Out), out)
return nil
}
func (r *Renderer) resetPrompt(lines int) {
// clean out current line in case tmpl didnt end in newline
cursor := r.NewCursor()
cursor.HorizontalAbsolute(0)
terminal.EraseLine(r.stdio.Out, terminal.ERASE_LINE_ALL)
// clean up what we left behind last time
for i := 0; i < lines; i++ {
cursor.PreviousLine(1)
terminal.EraseLine(r.stdio.Out, terminal.ERASE_LINE_ALL)
}
}
func (r *Renderer) Render(tmpl string, data interface{}) error {
r.resetPrompt(r.lineCount)
// render the template summarizing the current state
out, err := core.RunTemplate(tmpl, data)
if err != nil {
return err
}
// keep track of how many lines are printed so we can clean up later
r.lineCount = strings.Count(out, "\n")
// print the summary
fmt.Fprint(terminal.NewAnsiStdout(r.stdio.Out), out)
// nothing went wrong
return nil
}