forked from pb33f/wiretap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream_output.go
62 lines (53 loc) · 1.46 KB
/
stream_output.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
// Copyright 2024 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: AGPL
package daemon
import (
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/pb33f/libopenapi-validator/errors"
"github.com/pterm/pterm"
"os"
"sync"
)
func (ws *WiretapService) listenForValidationErrors() {
ws.streamViolations = []*errors.ValidationError{}
var lock sync.RWMutex
json := jsoniter.ConfigCompatibleWithStandardLibrary
_ = os.Remove(ws.reportFile)
f, err := os.OpenFile(ws.reportFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
pterm.Error.Println("cannot stream violations: " + err.Error())
return
}
go func() {
defer f.Close()
if _, e := f.WriteString("[]"); e != nil {
pterm.Error.Println("cannot write violation to stream: " + err.Error())
}
for {
select {
case violations := <-ws.streamChan:
if ws.stream {
lock.Lock()
fi, _ := f.Stat()
_ = os.Truncate(ws.reportFile, fi.Size()-1)
if fi.Size() > 2 {
_, _ = f.WriteString(",\n")
}
ws.streamViolations = append(ws.streamViolations, violations...)
for i, v := range violations {
bytes, _ := json.Marshal(v)
if _, e := f.WriteString(fmt.Sprintf("%s", bytes)); e != nil {
pterm.Error.Println("cannot write violation to stream: " + err.Error())
}
if i > len(violations)-1 {
_, _ = f.WriteString(",\n")
}
}
_, _ = f.WriteString("]")
lock.Unlock()
}
}
}
}()
}