forked from sbreitf1/go-console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole.go
More file actions
344 lines (286 loc) · 7.4 KB
/
console.go
File metadata and controls
344 lines (286 loc) · 7.4 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package console
import (
"fmt"
"os"
"reflect"
"strings"
"unicode/utf8"
"golang.org/x/term"
)
const (
listSpaceLen = 2
)
var (
// DefaultInput can be used to redirect input sources.
DefaultInput Input
// DefaultOutput can be used to redirect output destinations.
DefaultOutput Output
newline string
)
// Input defines functionality to handle console input.
type Input interface {
ReadLine() (string, error)
ReadPassword() (string, error)
BeginReadKey() error
ReadKey() (Key, rune, error)
EndReadKey() error
}
// Output defines functionality to handle console output and os responses.
type Output interface {
Print(string) (int, error)
GetSize() (int, int, error)
SupportsColors() bool
Exit(int)
}
type defaultInput struct {
lastCharWasCR bool
}
type defaultOutput struct {
}
func init() {
DefaultInput = &defaultInput{}
DefaultOutput = &defaultOutput{}
newline = fmt.Sprintln()
}
func (d *defaultOutput) Print(str string) (int, error) {
return fmt.Print(str)
}
// Print writes a set of objects separated by whitespaces to Stdout.
func Print(a ...any) (int, error) {
return DefaultOutput.Print(fmt.Sprint(a...))
}
// Printf writes a formatted string to Stdout.
func Printf(format string, a ...any) (int, error) {
return DefaultOutput.Print(fmt.Sprintf(format, a...))
}
// Println writes a set of objects separated by whitespaces to Stdout and ends the line.
func Println(a ...any) (int, error) {
return DefaultOutput.Print(fmt.Sprintln(a...))
}
// Printlnf writes a formatted string to Stdout and ends the line.
func Printlnf(format string, a ...any) (int, error) {
return Println(fmt.Sprintf(format, a...))
}
// Fatal calls Print and exits with code 1.
func Fatal(a ...any) {
fatalWrapper(Print(a...))
}
// Fatalf calls Printf and exits with code 1.
func Fatalf(format string, a ...any) {
fatalWrapper(Printf(format, a...))
}
// Fatalln calls Println and exits with code 1.
func Fatalln(a ...any) {
fatalWrapper(Println(a...))
}
// Fatallnf calls Printlnf and exits with code 1.
func Fatallnf(format string, a ...any) {
fatalWrapper(Printlnf(format, a...))
}
func (d *defaultOutput) Exit(code int) {
os.Exit(code)
}
func fatalWrapper(int, error) {
DefaultOutput.Exit(1)
}
// PrintList prints all array or map values in a regular grid.
func PrintList(obj any) error {
width, _, err := GetSize()
if err != nil {
return err
}
list := toList(obj)
maxItemLen := 0
for _, item := range list {
if len(item) > maxItemLen {
maxItemLen = len(item)
}
}
var sb strings.Builder
space := strings.Repeat(" ", listSpaceLen)
itemsPerLine := (width + listSpaceLen) / (maxItemLen + listSpaceLen)
lineCount := len(list) / itemsPerLine
if len(list) > (lineCount * itemsPerLine) {
lineCount++
}
if itemsPerLine == 0 {
// fallback for very small terminals (or exceedingly large list items)
itemsPerLine = 1
lineCount = len(list)
}
for l := 0; l < lineCount; l++ {
for i := 0; i < itemsPerLine; i++ {
index := l*itemsPerLine + i
if index >= len(list) {
break
}
if i > 0 {
sb.WriteString(space)
}
sb.WriteString(list[index])
sb.WriteString(strings.Repeat(" ", maxItemLen-len(list[index])))
}
sb.WriteString(newline)
}
_, err = Print(sb.String())
return err
}
func toList(obj any) []string {
if obj == nil {
return nil
}
var list []string
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
toString := func(v reflect.Value) string {
return fmt.Sprintf("%v", v.Interface())
}
switch t.Kind() {
case reflect.Array:
fallthrough
case reflect.Slice:
list = make([]string, v.Len())
for i := 0; i < v.Len(); i++ {
list[i] = toString(v.Index(i))
}
case reflect.Map:
list = make([]string, v.Len())
i := 0
for it := v.MapRange(); it.Next(); {
list[i] = toString(it.Value())
i++
}
}
return list
}
func (d *defaultOutput) GetSize() (int, int, error) {
return term.GetSize(int(os.Stdout.Fd()))
}
// GetSize returns the current terminal dimensions in characters.
func GetSize() (int, int, error) {
return DefaultOutput.GetSize()
}
func (d *defaultOutput) SupportsColors() bool {
return supportsColors()
}
// SupportsColors returns true when the current terminal supports ANSI colors.
func SupportsColors() bool {
return DefaultOutput.SupportsColors()
}
func (d *defaultInput) ReadLine() (string, error) {
//TODO configurable encoding
return d.readLine(d.readRuneUTF8)
}
func (d *defaultInput) readLine(readRune func() (rune, error)) (string, error) {
var sb strings.Builder
for {
r, err := readRune()
if err != nil {
return sb.String(), err
}
if r == '\r' {
d.lastCharWasCR = true
return sb.String(), nil
} else if r == '\n' {
if d.lastCharWasCR {
// just ignore that char to be compatible with windows \r\n
d.lastCharWasCR = false
} else {
d.lastCharWasCR = false
return sb.String(), nil
}
} else {
d.lastCharWasCR = false
sb.WriteRune(r)
}
}
}
func (*defaultInput) readRuneANSI() (rune, error) {
var buf = [1]byte{0}
_, err := os.Stdin.Read(buf[:])
if err != nil {
return 0, err
}
return rune(buf[0]), nil
}
func (*defaultInput) readRuneUTF8() (rune, error) {
// utf8 runes can take 1 up to 4 bytes
var buf = [4]byte{0}
_, err := os.Stdin.Read(buf[0:1])
if err != nil {
return 0, err
}
// most common case: rune takes exactly one byte
if !utf8.FullRune(buf[0:1]) {
// not complete yet? read next byte and check again
for i := 1; i < 4; i++ {
// put next byte into buffer
_, err := os.Stdin.Read(buf[i : i+1])
if err != nil {
return 0, err
}
if i < 3 {
// skip check for last rune -> will terminate either way
if utf8.FullRune(buf[0 : i+1]) {
break
}
}
}
}
r, _ := utf8.DecodeRune(buf[:])
return r, nil
}
// ReadLine reads a line from Stdin.
//
// This method should not be used in conjunction with Stdin read from other packages as it might leave an orphaned '\n' in the input buffer for '\r\n' line breaks.
func ReadLine() (string, error) {
return DefaultInput.ReadLine()
}
func (d *defaultInput) ReadPassword() (string, error) {
var pw string
if err := withoutEcho(func() error {
line, err := d.ReadLine()
pw = line
return err
}); err != nil {
return "", err
}
// print suppressed line-feed
Println()
return pw, nil
}
// ReadPassword reads a line from Stdin while hiding the user input.
//
// This method should not be used in conjunction with Stdin read from other packages as it might leave an orphaned '\n' in the input buffer for '\r\n' line breaks.
func ReadPassword() (string, error) {
return DefaultInput.ReadPassword()
}
func (d *defaultInput) BeginReadKey() error {
return beginReadKey()
}
func (d *defaultInput) ReadKey() (Key, rune, error) {
return readKey()
}
func (d *defaultInput) EndReadKey() error {
return endReadKey()
}
// BeginReadKey opens a raw TTY and allows you to use ReadKey.
func BeginReadKey() error {
return DefaultInput.BeginReadKey()
}
// ReadKey returns a key and the corresponding rune or an error. BeginReadKey needs to be called first.
func ReadKey() (Key, rune, error) {
return DefaultInput.ReadKey()
}
// EndReadKey closes the raw TTY opened by BeginReadKey and discards all unprocessed key events.
func EndReadKey() error {
return DefaultInput.EndReadKey()
}
// WithReadKeyContext executes the given function with surrounding BeginReadKey and EndReadKey calls.
func WithReadKeyContext(f func() error) error {
if err := DefaultInput.BeginReadKey(); err != nil {
return err
}
defer DefaultInput.EndReadKey()
return f()
}