forked from AlecAivazis/survey
-
Notifications
You must be signed in to change notification settings - Fork 4
/
renderer.go
62 lines (51 loc) · 1.5 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
package core
import (
"strings"
"github.com/AlecAivazis/survey/terminal"
)
type Renderer struct {
lineCount int
errorLineCount int
}
var ErrorTemplate = `{{color "red"}}{{ ErrorIcon }} Sorry, your reply was invalid: {{.Error}}{{color "reset"}}
`
func (r *Renderer) Error(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 := RunTemplate(ErrorTemplate, invalid)
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
terminal.Print(out)
return nil
}
func (r *Renderer) resetPrompt(lines int) {
// clean out current line in case tmpl didnt end in newline
terminal.CursorHorizontalAbsolute(0)
terminal.EraseLine(terminal.ERASE_LINE_ALL)
// clean up what we left behind last time
for i := 0; i < lines; i++ {
terminal.CursorPreviousLine(1)
terminal.EraseLine(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 := 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
terminal.Print(out)
// nothing went wrong
return nil
}