-
Notifications
You must be signed in to change notification settings - Fork 9
/
defaultout.go
91 lines (78 loc) · 1.75 KB
/
defaultout.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
package es_stdout
import (
"errors"
"github.com/mattn/go-colorable"
"github.com/watermint/toolbox/essentials/log/esl"
"github.com/watermint/toolbox/essentials/terminal/es_terminfo"
"github.com/watermint/toolbox/quality/infra/qt_secure"
"io"
"io/ioutil"
"os"
)
var (
ErrorGeneralIOFailure = errors.New("general i/o error")
)
type Feature interface {
IsQuiet() bool
IsTest() bool
}
func newDefaultOut(test, quiet bool) io.WriteCloser {
if quiet {
return &syncOut{co: ioutil.Discard}
}
if test {
if qt_secure.IsSecureEndToEndTest() {
return &syncOut{co: ioutil.Discard}
} else {
return &syncOut{co: os.Stdout}
}
} else {
if es_terminfo.IsOutColorTerminal() {
return newWriteCloser(colorable.NewColorableStdout())
} else {
return newWriteCloser(os.Stdout)
}
}
}
func NewDiscard() io.WriteCloser {
return &syncOut{co: ioutil.Discard}
}
func NewDefaultOut(feature Feature) io.WriteCloser {
return newDefaultOut(feature.IsTest(), feature.IsQuiet())
}
func NewTestOut() io.WriteCloser {
return newDefaultOut(true, false)
}
func NewDirectOut() io.WriteCloser {
return newDefaultOut(false, false)
}
func newWriteCloser(co io.Writer) io.WriteCloser {
return newSync(co)
}
func newSync(co io.Writer) io.WriteCloser {
return &syncOut{
co: co,
}
}
type syncOut struct {
co io.Writer
}
func (z syncOut) Write(p []byte) (n int, err error) {
// Recovery option for I/O error
// https://github.com/watermint/toolbox/issues/411
defer func() {
if r := recover(); err != nil {
l := esl.Default()
l.Debug("Recovery from the syncOut error", esl.Any("r", r))
if errVal, ok := r.(error); ok {
err = errVal
} else {
err = ErrorGeneralIOFailure
}
}
}()
return z.co.Write(p)
}
func (z syncOut) Close() error {
return nil
}