-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.go
74 lines (63 loc) · 1.33 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
package system
import (
"fmt"
"io"
"github.com/fatih/color"
input "github.com/tcnksm/go-input"
"github.com/izumin5210/dform/util/log"
)
// UI is an interface to abstract interactions with users.
type UI interface {
Output(string)
Warn(string)
Error(string)
Confirm(string) (bool, error)
}
type uiImpl struct {
in io.Reader
out io.Writer
err io.Writer
inputUI *input.UI
}
var (
fprintlnWarn = color.New(color.FgYellow).FprintlnFunc()
fprintlnError = color.New(color.FgYellow).FprintlnFunc()
)
// NewUI creates new UI object.
func NewUI(in io.Reader, out, err io.Writer) UI {
return &uiImpl{
in: in,
out: out,
err: err,
inputUI: &input.UI{
Reader: in,
Writer: out,
},
}
}
func (i *uiImpl) Output(msg string) {
fmt.Fprintln(i.out, msg)
}
func (i *uiImpl) Warn(msg string) {
fprintlnWarn(i.err, msg)
}
func (i *uiImpl) Error(msg string) {
fprintlnError(i.err, msg)
}
func (i *uiImpl) Confirm(msg string) (bool, error) {
ans, err := i.inputUI.Ask(fmt.Sprintf("%s [Y/n]", msg), &input.Options{
HideOrder: true,
Loop: true,
ValidateFunc: func(ans string) error {
log.Debug("receive user input", "query", msg, "input", ans)
if ans != "Y" && ans != "n" {
return fmt.Errorf("input must be Y or n")
}
return nil
},
})
if err != nil {
return false, err
}
return ans == "Y", nil
}