This repository has been archived by the owner on Mar 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
102 lines (83 loc) · 1.87 KB
/
env.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
102
// nolint forbidigo
package testhelper
import (
"bytes"
"io"
"os"
"regexp"
"strings"
"github.com/acarl005/stripansi"
"github.com/spf13/cast"
)
type EnvProvider interface {
MustGet(key string) string
}
// ReplaceEnvsString replaces ENVs in given string.
func ReplaceEnvsString(str string, provider EnvProvider) string {
return regexp.
MustCompile(`%%[a-zA-Z0-9\-_]+%%`).
ReplaceAllStringFunc(str, func(s string) string {
return provider.MustGet(strings.Trim(s, `%`))
})
}
// stripAnsiWriter strips ANSI characters from
type stripAnsiWriter struct {
buf *bytes.Buffer
writer io.Writer
}
func newStripAnsiWriter(writer io.Writer) *stripAnsiWriter {
return &stripAnsiWriter{
buf: &bytes.Buffer{},
writer: writer,
}
}
func (w *stripAnsiWriter) writeBuffer() error {
if _, err := w.writer.Write([]byte(stripansi.Strip(w.buf.String()))); err != nil {
return err
}
w.buf.Reset()
return nil
}
func (w *stripAnsiWriter) Write(p []byte) (int, error) {
// Append to the buffer
n, err := w.buf.Write(p)
// We can only remove an ANSI escape seq if the whole expression is present.
// ... so if buffer contains new line -> flush
if bytes.Contains(w.buf.Bytes(), []byte("\n")) {
if err := w.writeBuffer(); err != nil {
return 0, err
}
}
return n, err
}
func (w *stripAnsiWriter) Close() error {
if err := w.writeBuffer(); err != nil {
return err
}
return nil
}
type nopCloser struct {
io.Writer
}
func (n *nopCloser) Close() error {
return nil
}
func TestIsVerbose() bool {
value := os.Getenv("TEST_VERBOSE")
if value == "" {
value = "false"
}
return cast.ToBool(value)
}
func VerboseStdout() io.WriteCloser {
if TestIsVerbose() {
return newStripAnsiWriter(os.Stdout)
}
return &nopCloser{io.Discard}
}
func VerboseStderr() io.WriteCloser {
if TestIsVerbose() {
return newStripAnsiWriter(os.Stderr)
}
return &nopCloser{io.Discard}
}