v0.0.236 cmdext.FailOnStdErr
This commit is contained in:
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
var ErrExitCode = errors.New("process exited with an unexpected exitcode")
|
||||
var ErrTimeout = errors.New("process did not exit after the specified timeout")
|
||||
var ErrStderrPrint = errors.New("process did print to stderr stream")
|
||||
|
||||
type CommandResult struct {
|
||||
StdOut string
|
||||
@@ -53,12 +54,27 @@ func run(opt CommandRunner) (CommandResult, error) {
|
||||
err error
|
||||
}
|
||||
|
||||
stderrFailChan := make(chan bool)
|
||||
|
||||
outputChan := make(chan resultObj)
|
||||
go func() {
|
||||
// we need to first fully read the pipes and then call Wait
|
||||
// see https://pkg.go.dev/os/exec#Cmd.StdoutPipe
|
||||
|
||||
stdout, stderr, stdcombined, err := preader.Read(opt.listener)
|
||||
listener := make([]CommandListener, 0)
|
||||
listener = append(listener, opt.listener...)
|
||||
|
||||
if opt.enforceNoStderr {
|
||||
listener = append(listener, genericCommandListener{
|
||||
_readRawStderr: langext.Ptr(func(v []byte) {
|
||||
if len(v) > 0 {
|
||||
stderrFailChan <- true
|
||||
}
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
stdout, stderr, stdcombined, err := preader.Read(listener)
|
||||
if err != nil {
|
||||
outputChan <- resultObj{stdout, stderr, stdcombined, err}
|
||||
_ = cmd.Process.Kill()
|
||||
@@ -115,6 +131,34 @@ func run(opt CommandRunner) (CommandResult, error) {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
case <-stderrFailChan:
|
||||
_ = cmd.Process.Kill()
|
||||
for _, lstr := range opt.listener {
|
||||
lstr.Timeout()
|
||||
}
|
||||
|
||||
if fallback, ok := syncext.ReadChannelWithTimeout(outputChan, 32*time.Millisecond); ok {
|
||||
// most of the time the cmd.Process.Kill() should also have finished the pipereader
|
||||
// and we can at least return the already collected stdout, stderr, etc
|
||||
res := CommandResult{
|
||||
StdOut: fallback.stdout,
|
||||
StdErr: fallback.stderr,
|
||||
StdCombined: fallback.stdcombined,
|
||||
ExitCode: -1,
|
||||
CommandTimedOut: false,
|
||||
}
|
||||
return res, ErrStderrPrint
|
||||
} else {
|
||||
res := CommandResult{
|
||||
StdOut: "",
|
||||
StdErr: "",
|
||||
StdCombined: "",
|
||||
ExitCode: -1,
|
||||
CommandTimedOut: false,
|
||||
}
|
||||
return res, ErrStderrPrint
|
||||
}
|
||||
|
||||
case outobj := <-outputChan:
|
||||
if exiterr, ok := outobj.err.(*exec.ExitError); ok {
|
||||
excode := exiterr.ExitCode()
|
||||
|
Reference in New Issue
Block a user