forked from harness/gitness
/
writer.go
72 lines (55 loc) · 1.42 KB
/
writer.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
package build
import (
//"bytes"
"fmt"
"io"
"strings"
)
var (
// the prefix used to determine if this is
// data that should be stripped from the output
prefix = []byte("#DRONE:")
// default limit to use when streaming build output.
DefaultLimit = 2000000
)
// custom writer to intercept the build
// output
type writer struct {
io.Writer
length int
}
// Write appends the contents of p to the buffer. It will
// scan for DRONE special formatting codes embedded in the
// output, and will alter the output accordingly.
func (w *writer) Write(p []byte) (n int, err error) {
// ensure we haven't exceeded the limit
if w.length > DefaultLimit {
w.Writer.Write([]byte("Truncating build output ..."))
return len(p), nil
}
// track the number of bytes written to the
// buffer so that we can limit it.
w.length += len(p)
lines := strings.Split(string(p), "\n")
for i, line := range lines {
if strings.HasPrefix(line, "#DRONE:") {
var cmd string
// extract the command (base16 encoded)
// from the output
fmt.Sscanf(line[7:], "%x", &cmd)
// echo the decoded command
cmd = fmt.Sprintf("$ %s", cmd)
w.Writer.Write([]byte(cmd))
} else {
w.Writer.Write([]byte(line))
}
if i < len(lines)-1 {
w.Writer.Write([]byte("\n"))
}
}
return len(p), nil
}
// WriteString appends the contents of s to the buffer.
func (w *writer) WriteString(s string) (n int, err error) {
return w.Write([]byte(s))
}