Skip to content

Commit

Permalink
Merge pull request #2025 from giuseppe/fix-archive-filter-error-repor…
Browse files Browse the repository at this point in the history
…ting

archive: improve filter error reporting
  • Loading branch information
openshift-merge-bot[bot] authored Jul 15, 2024
2 parents 98ad80d + 91f150f commit a9357dd
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions pkg/archive/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ func getFilterPath(name string) string {
return path.(string)
}

type errorRecordingReader struct {
r io.Reader
err error
}

func (r *errorRecordingReader) Read(p []byte) (int, error) {
n, err := r.r.Read(p)
if r.err == nil && err != io.EOF {
r.err = err
}
return n, err
}

// tryProcFilter tries to run the command specified in args, passing input to its stdin and returning its stdout.
// cleanup() is a caller provided function that will be called when the command finishes running, regardless of
// whether it succeeds or fails.
Expand All @@ -38,22 +51,20 @@ func tryProcFilter(args []string, input io.Reader, cleanup func()) (io.ReadClose

var stderrBuf bytes.Buffer

inputWithError := &errorRecordingReader{r: input}

r, w := io.Pipe()
cmd := exec.Command(path, args[1:]...)
cmd.Stdin = input
cmd.Stdin = inputWithError
cmd.Stdout = w
cmd.Stderr = &stderrBuf
go func() {
err := cmd.Run()
if err != nil && stderrBuf.Len() > 0 {
b := make([]byte, 1)
// if there is an error reading from input, prefer to return that error
_, errRead := input.Read(b)
if errRead != nil && errRead != io.EOF {
err = errRead
} else {
err = fmt.Errorf("%s: %w", strings.TrimRight(stderrBuf.String(), "\n"), err)
}
// if there is an error reading from input, prefer to return that error
if inputWithError.err != nil {
err = inputWithError.err
} else if err != nil && stderrBuf.Len() > 0 {
err = fmt.Errorf("%s: %w", strings.TrimRight(stderrBuf.String(), "\n"), err)
}
w.CloseWithError(err) // CloseWithErr(nil) == Close()
cleanup()
Expand Down

0 comments on commit a9357dd

Please sign in to comment.