-
Notifications
You must be signed in to change notification settings - Fork 0
/
printer.go
86 lines (72 loc) · 1.55 KB
/
printer.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
package gctrl
import (
"fmt"
"io"
"reflect"
)
type colorID int
const (
black colorID = iota + 30
red
green
yellow
blue
magenta
cyan
white
)
type printer struct {
Writer io.Writer
Coloring bool
}
func (this *printer) Normal(format string, args ...interface{}) {
this.write(green, format, args...)
}
func (this *printer) Error(format string, args ...interface{}) {
this.write(red, format, args...)
}
func (this *printer) Prompt() {
this.Normal("%s", `type '_list("")' to show registered function list`)
}
func (this *printer) Result(results []reflect.Value) {
if len(results) == 0 {
this.Normal("%s", "<void>")
return
}
printer := this.Normal
if hasError(results) {
printer = this.Error
}
for i, result := range results {
typ := fmt.Sprint(result.Type())
kind := fmt.Sprint(result.Kind())
if typ == kind {
printer("[%d] %v: %v", i, typ, result)
} else {
printer("[%d] %v(%v): %v", i, typ, kind, result)
}
}
}
func (this *printer) write(color colorID, format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
if this.Coloring {
fmt.Fprintln(this.Writer, colorize(msg, color))
} else {
fmt.Fprintln(this.Writer, msg)
}
}
func hasError(results []reflect.Value) bool {
for _, result := range results {
if isError(result) && !result.IsNil() {
return true
}
}
return false
}
func isError(value reflect.Value) bool {
typ := value.Type()
return typ.PkgPath() == "" && typ.Name() == "error"
}
func colorize(text string, color colorID) string {
return fmt.Sprintf("\033[%dm%s\033[0m", color, text)
}