-
Notifications
You must be signed in to change notification settings - Fork 0
/
stderr.go
105 lines (89 loc) · 2.2 KB
/
stderr.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
package lvm2go
import (
"bytes"
"errors"
"slices"
)
const LVMWarningPrefix = "WARNING: "
var stdErrNewLine = []byte("\n")
type LVMStdErr interface {
error
Bytes() []byte
Lines(trimPrefix bool) [][]byte
Warnings() []Warning
}
// AsLVMStdErr returns the LVMStdErr from the error if it exists and a bool indicating if LVMStdErr is present or not.
func AsLVMStdErr(err error) (LVMStdErr, bool) {
var lvmStdErr LVMStdErr
ok := errors.As(err, &lvmStdErr)
return lvmStdErr, ok
}
func NewLVMStdErr(stderr []byte) LVMStdErr {
if len(stderr) == 0 {
return nil
}
lines := bytes.Split(stderr, stdErrNewLine)
for i := range lines {
lines[i] = bytes.TrimSpace(lines[i])
}
// Remove empty lines, e.g. due to double newlines
lines = slices.DeleteFunc(lines, func(line []byte) bool {
return len(line) == 0
})
// Sort and compact the lines, removing duplicates
slices.SortStableFunc(lines, func(a, b []byte) int {
return bytes.Compare(a, b)
})
lines = slices.CompactFunc(lines, func(a, b []byte) bool {
return bytes.Equal(a, b)
})
return &stdErr{lines: lines}
}
type stdErr struct {
lines [][]byte
}
func (e *stdErr) Error() string {
return string(e.Bytes())
}
func (e *stdErr) Bytes() []byte {
return bytes.Join(e.lines, stdErrNewLine)
}
func (e *stdErr) Lines(trimPrefix bool) [][]byte {
if trimPrefix {
trimmed := make([][]byte, len(e.lines))
for i, line := range e.lines {
trimmed[i] = bytes.TrimPrefix(line, []byte(LVMWarningPrefix))
}
return trimmed
}
return e.lines
}
func (e *stdErr) ExcludeWarnings() *stdErr {
return &stdErr{lines: slices.DeleteFunc(e.lines, func(line []byte) bool {
return bytes.HasPrefix(line, []byte(LVMWarningPrefix))
})}
}
func (e *stdErr) Warnings() []Warning {
warnings := make([]Warning, 0, len(e.lines))
for _, line := range e.lines {
if warning := NewWarning(line); warning != nil {
warnings = append(warnings, warning)
}
}
return warnings
}
type Warning interface {
error
}
func NewWarning(raw []byte) Warning {
if idx := bytes.LastIndex(raw, []byte(LVMWarningPrefix)); idx > 0 {
return &warning{msg: raw[idx+len(LVMWarningPrefix):]}
}
return nil
}
type warning struct {
msg []byte
}
func (w *warning) Error() string {
return string(w.msg)
}