-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.go
131 lines (108 loc) · 2.49 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
package ui
import (
"fmt"
"io"
"os"
"sync"
)
// Level represents the verbosity level.
type Level int
const (
// Trace shows all messages.
Trace Level = iota
// Debug shows Debug, Info, Warn, and Error messages.
Debug
// Info shows Info, Warn, and Error messages.
Info
// Warn shows Warn and Error messages.
Warn
// Error shows only Error messages.
Error
// None does not show any messages.
None
)
// UI is the interface for interacting with users in command-line applications.
type UI interface {
// Output method independent of the verbosity level
Printf(format string, a ...interface{})
// Leveled output methods
GetLevel() Level
SetLevel(l Level)
Tracef(s Style, format string, a ...interface{})
Debugf(s Style, format string, a ...interface{})
Infof(s Style, format string, a ...interface{})
Warnf(s Style, format string, a ...interface{})
Errorf(s Style, format string, a ...interface{})
}
// ui implements the UI interface.
type ui struct {
sync.Mutex
level Level
writer io.WriteCloser
errorWriter io.WriteCloser
}
// New creates a new user interface.
// This is a concurrent-safe UI and can be used across multiple Go routines.
func New(level Level) UI {
return &ui{
level: level,
writer: os.Stdout,
errorWriter: os.Stderr,
}
}
func (u *ui) Printf(format string, a ...interface{}) {
u.Lock()
defer u.Unlock()
s := fmt.Sprintf(format, a...)
fmt.Fprintln(u.writer, s)
}
func (u *ui) GetLevel() Level {
u.Lock()
defer u.Unlock()
return u.level
}
func (u *ui) SetLevel(l Level) {
u.Lock()
defer u.Unlock()
u.level = l
}
func (u *ui) Tracef(style Style, format string, a ...interface{}) {
u.Lock()
defer u.Unlock()
if u.level <= Trace {
s := style.sprintf(format, a...)
fmt.Fprintln(u.writer, s)
}
}
func (u *ui) Debugf(style Style, format string, a ...interface{}) {
u.Lock()
defer u.Unlock()
if u.level <= Debug {
s := style.sprintf(format, a...)
fmt.Fprintln(u.writer, s)
}
}
func (u *ui) Infof(style Style, format string, a ...interface{}) {
u.Lock()
defer u.Unlock()
if u.level <= Info {
s := style.sprintf(format, a...)
fmt.Fprintln(u.writer, s)
}
}
func (u *ui) Warnf(style Style, format string, a ...interface{}) {
u.Lock()
defer u.Unlock()
if u.level <= Warn {
s := style.sprintf(format, a...)
fmt.Fprintln(u.writer, s)
}
}
func (u *ui) Errorf(style Style, format string, a ...interface{}) {
u.Lock()
defer u.Unlock()
if u.level <= Error {
s := style.sprintf(format, a...)
fmt.Fprintln(u.errorWriter, s)
}
}