-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilewriter.go
101 lines (88 loc) · 1.66 KB
/
filewriter.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
package goolog2
import (
"os"
atty "github.com/mattn/go-isatty"
"github.com/xo/terminfo"
)
type simpleFileWriter struct {
file *os.File
owner bool
tinfo *terminfo.Terminfo
}
func newSimpleFileWriter(
file *os.File,
owner bool,
) FileWriter {
writer := &simpleFileWriter{
file: file,
owner: owner,
}
/* -- get the terminfo object */
if isatty := atty.IsTerminal(file.Fd()); isatty {
tinfo, err := terminfo.LoadFromEnv()
if err == nil {
writer.tinfo = tinfo
}
}
return writer
}
func (this *simpleFileWriter) Close() error {
if !this.owner || this.file == nil {
return nil
}
err := this.file.Close()
this.file = nil
return err
}
func (this *simpleFileWriter) Stat() os.FileInfo {
if this.file == nil {
return nil
}
stat, err := this.file.Stat()
if err != nil {
return nil
}
return stat
}
func (this *simpleFileWriter) Sync() {
if this.file != nil {
this.file.Sync()
}
}
func (this *simpleFileWriter) Write(
p []byte,
) (int, error) {
if this.file == nil {
return 0, os.ErrClosed
}
return this.file.Write(p)
}
func (this *simpleFileWriter) ChangeColor(
color Color,
) {
if this.tinfo != nil && this.file != nil {
/* -- select color */
var tcolor int
switch color {
case RED:
tcolor = 1 /* -- red */
case YELLOW:
tcolor = 3 /* -- yellow */
case BLUE:
tcolor = 2 /* -- green */
default:
tcolor = -1
}
/* -- colorize the output */
if tcolor > 0 {
this.file.WriteString(
this.tinfo.Printf(terminfo.SetAForeground, tcolor))
}
}
}
func (this *simpleFileWriter) ResetColor() {
if this.tinfo != nil && this.file != nil {
this.file.WriteString(
this.tinfo.Printf(terminfo.ExitAttributeMode))
}
}