-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathxterm.go
99 lines (83 loc) · 1.81 KB
/
xterm.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
package xterm
import (
"fmt"
"hash/crc64"
"io"
"math/rand"
"os"
"golang.org/x/term"
"oss.terrastruct.com/util-go/xos"
)
// See https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
const (
csi = "\x1b["
reset = csi + "0m"
Bold = csi + "1m"
Red = csi + "31m"
Green = csi + "32m"
Yellow = csi + "33m"
Blue = csi + "34m"
Magenta = csi + "35m"
Cyan = csi + "36m"
BrightRed = csi + "91m"
BrightGreen = csi + "92m"
BrightYellow = csi + "93m"
BrightBlue = csi + "94m"
BrightMagenta = csi + "95m"
BrightCyan = csi + "96m"
)
var colors = [...]string{
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
}
// isTTY checks whether the given writer is a *os.File TTY.
func isTTY(w io.Writer) bool {
f, ok := w.(interface {
Fd() uintptr
})
return ok && term.IsTerminal(int(f.Fd()))
}
func shouldColor(env *xos.Env, w io.Writer) bool {
eb, err := env.Bool("COLOR")
if eb != nil {
return *eb
}
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("xterm: %v", err))
}
if env.Getenv("TERM") == "dumb" {
return false
}
return isTTY(w)
}
func Tput(env *xos.Env, w io.Writer, caps, s string) string {
if caps == "" {
return s
}
if !shouldColor(env, w) {
return s
}
return caps + s + reset
}
func Prefix(env *xos.Env, w io.Writer, caps, s string) string {
s = fmt.Sprintf("%s", s)
return Tput(env, w, caps, s) + ":"
}
var crc64Table = crc64.MakeTable(crc64.ISO)
// CC meaning constant color. So constant color prefix.
func CCPrefix(env *xos.Env, w io.Writer, s string) string {
sum := crc64.Checksum([]byte(s), crc64Table)
rand := rand.New(rand.NewSource(int64(sum)))
color := colors[rand.Intn(len(colors))]
return Prefix(env, w, color, s)
}