/
cmd_run_result.go
64 lines (55 loc) · 1.31 KB
/
cmd_run_result.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
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package exec
import (
"fmt"
"os/exec"
"regexp"
"strings"
)
var (
trailingSpace = regexp.MustCompile("\\s+\n")
)
type CmdRunResult struct {
Stdout string
Stderr string
ExitCode int
Error error
Finished bool
}
func NewCmdRunResultWithErr(err error) CmdRunResult {
var result CmdRunResult
result.AttachErrorf("%s", err)
return result
}
func (r *CmdRunResult) AttachErrorf(msg string, err error) {
r.Finished = true
if err != nil {
r.ExitCode = -1
if exitError, ok := err.(*exec.ExitError); ok {
r.ExitCode = exitError.ExitCode()
}
if err.Error() == "exit status 1" {
r.Error = fmt.Errorf(msg, "Error (see .status.usefulErrorMessage for details)")
} else {
r.Error = fmt.Errorf(msg, err)
}
}
}
func (r CmdRunResult) ErrorStr() string {
if r.Error != nil {
return r.Error.Error()
}
return ""
}
func (r CmdRunResult) WithFriendlyYAMLStrings() CmdRunResult {
// YAML can format muliline strings nicely
// if they do not have trailing spaces right before newlines
return CmdRunResult{
Stdout: trailingSpace.ReplaceAllString(strings.TrimSpace(r.Stdout), "\n"),
Stderr: trailingSpace.ReplaceAllString(strings.TrimSpace(r.Stderr), "\n"),
ExitCode: r.ExitCode,
Error: r.Error,
Finished: r.Finished,
}
}