forked from Azure/dalec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
252 lines (209 loc) · 4.92 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"path"
"path/filepath"
"runtime/debug"
"strings"
"time"
"github.com/pkg/errors"
)
func main() {
tmp, err := os.MkdirTemp("", "test2json2gha-")
if err != nil {
panic(err)
}
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
slog.SetDefault(logger)
info, _ := debug.ReadBuildInfo()
var mod string
if info != nil {
mod = info.Main.Path
}
// Set TMPDIR so that [os.CreateTemp] can use an empty string as the dir
// and wind up in our dir.
os.Setenv("TMPDIR", tmp)
cleanup := func() { os.RemoveAll(tmp) }
anyFail, err := do(os.Stdin, os.Stdout, mod)
if err != nil {
fmt.Fprintf(os.Stderr, "%+v", err)
cleanup()
os.Exit(1)
}
cleanup()
if anyFail {
// In case pipefail is not enabled, make sure we exit non-zero
os.Exit(2)
}
}
// TestEvent is the go test2json event data structure we receive from `go test`
// This is defined in https://pkg.go.dev/cmd/test2json#hdr-Output_Format
type TestEvent struct {
Time time.Time
Action string
Package string
Test string
Elapsed float64 // seconds
Output string
}
// TestResult is where we collect all the data about a test
type TestResult struct {
output *os.File
failed bool
pkg string
name string
elapsed float64
}
func (r *TestResult) Close() {
r.output.Close()
}
func do(in io.Reader, out io.Writer, modName string) (bool, error) {
dec := json.NewDecoder(in)
te := &TestEvent{}
outs := make(map[string]*TestResult)
defer func() {
for _, tr := range outs {
tr.Close()
}
}()
getOutputStream := func() (*TestResult, error) {
key := path.Join(te.Package, te.Test)
tr := outs[key]
if tr == nil {
f, err := os.CreateTemp("", strings.Replace(key, "/", "-", -1))
if err != nil {
return nil, errors.WithStack(err)
}
tr = &TestResult{output: f}
outs[key] = tr
}
return tr, nil
}
for {
*te = TestEvent{}
if err := dec.Decode(te); err != nil {
if err == io.EOF {
break
}
return false, errors.WithStack(err)
}
if te.Test == "" {
// Don't bother processing events that aren't specfically for a test
// Go adds extra events in for package level info that we don't need.
continue
}
tr, err := getOutputStream()
if err != nil {
return false, err
}
if err := handlEvent(te, tr); err != nil {
slog.Error("Error handing event test event", "error", err)
}
}
buf := bufio.NewWriter(out)
var anyFail bool
for _, tr := range outs {
if tr.failed {
anyFail = true
}
if err := writeResult(tr, buf, modName); err != nil {
slog.Error("Error writing result", "error", err)
continue
}
if err := buf.Flush(); err != nil {
slog.Error("%v", err)
}
}
return anyFail, nil
}
func handlEvent(te *TestEvent, tr *TestResult) error {
if te.Output != "" {
_, err := tr.output.Write([]byte(te.Output))
if err != nil {
return errors.Wrap(err, "error collecting test event output")
}
}
tr.pkg = te.Package
tr.name = te.Test
tr.elapsed = te.Elapsed
if te.Action == "fail" {
tr.failed = true
}
return nil
}
func writeResult(tr *TestResult, out io.Writer, modName string) error {
if tr.name == "" {
return nil
}
if _, err := tr.output.Seek(0, io.SeekStart); err != nil {
return fmt.Errorf("error seeking to beginning of test output: %w", err)
}
pkg := strings.TrimPrefix(tr.pkg, modName)
pkg = strings.TrimPrefix(pkg, "/")
group := pkg
if group != "" && tr.name != "" {
group += "."
}
group += tr.name
var prefix string
if tr.failed {
// Adds a red X emoji to the front of the group name to more easily spot
// failures
prefix = "\u274c "
}
dur := time.Duration(tr.elapsed * float64(time.Second))
fmt.Fprintln(out, "::group::"+prefix+group, dur)
defer func() {
fmt.Fprintln(out, "::endgroup::")
}()
dt, err := io.ReadAll(tr.output)
if err != nil {
return fmt.Errorf("error reading test output: %w", err)
}
if !tr.failed {
if _, err := out.Write(dt); err != nil {
return fmt.Errorf("error writing test output to output stream: %w", err)
}
return nil
}
scanner := bufio.NewScanner(bytes.NewReader(dt))
var (
file, line string
)
buf := bytes.NewBuffer(nil)
for scanner.Scan() {
txt := scanner.Text()
f, l, ok := getTestOutputLoc(txt)
if ok {
file = f
line = l
}
// %0A is the url encoded form of \n.
// This allows a multi-line message as an annotation
// See https://github.com/actions/toolkit/issues/193#issuecomment-605394935
buf.WriteString(txt + "%0A")
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("error reading test output: %w", err)
}
file = filepath.Join(pkg, file)
fmt.Fprintf(out, "::error file=%s,line=%s::%s\n", file, line, buf)
return nil
}
func getTestOutputLoc(s string) (string, string, bool) {
file, other, ok := strings.Cut(s, ":")
if !ok {
return "", "", false
}
line, _, ok := strings.Cut(other, ":")
if !ok {
return "", "", false
}
return strings.TrimSpace(file), line, true
}