diff --git a/README.md b/README.md index 2730385..9a8c7d4 100644 --- a/README.md +++ b/README.md @@ -333,7 +333,7 @@ Sinks are methods that return some data from a pipe, ending the pipeline and ext | [`Slice`](https://pkg.go.dev/github.com/bitfield/script#Pipe.Slice) | | data as `[]string`, error | | [`Stdout`](https://pkg.go.dev/github.com/bitfield/script#Pipe.Stdout) | standard output | bytes written, error | | [`String`](https://pkg.go.dev/github.com/bitfield/script#Pipe.String) | | data as `string`, error | -| [`Wait`](https://pkg.go.dev/github.com/bitfield/script#Pipe.Wait) | | none | +| [`Wait`](https://pkg.go.dev/github.com/bitfield/script#Pipe.Wait) | | error | | [`WriteFile`](https://pkg.go.dev/github.com/bitfield/script#Pipe.WriteFile) | specified file, truncating if it exists | bytes written, error | # What's new diff --git a/script.go b/script.go index 80c5d07..953ef68 100644 --- a/script.go +++ b/script.go @@ -374,6 +374,9 @@ func (p *Pipe) EncodeBase64() *Pipe { } // Error returns any error present on the pipe, or nil otherwise. +// Error is not a sink and does not wait until the pipe reaches +// completion. To wait for completion before returning the error, +// see [Pipe.Wait]. func (p *Pipe) Error() error { if p.mu == nil { // uninitialised pipe return nil @@ -874,14 +877,15 @@ func (p *Pipe) Tee(writers ...io.Writer) *Pipe { return p.WithReader(io.TeeReader(p.Reader, teeWriter)) } -// Wait reads the pipe to completion and discards the result. This is mostly -// useful for waiting until concurrent filters have completed (see -// [Pipe.Filter]). -func (p *Pipe) Wait() { +// Wait reads the pipe to completion and returns any error present on +// the pipe, or nil otherwise. This is mostly useful for waiting until +// concurrent filters have completed (see [Pipe.Filter]). +func (p *Pipe) Wait() error { _, err := io.Copy(io.Discard, p) if err != nil { p.SetError(err) } + return p.Error() } // WithError sets the error err on the pipe. diff --git a/script_test.go b/script_test.go index 7dbec43..296869a 100644 --- a/script_test.go +++ b/script_test.go @@ -1850,6 +1850,22 @@ func TestReadReturnsErrorGivenReadErrorOnPipe(t *testing.T) { } } +func TestWait_ReturnsErrorPresentOnPipe(t *testing.T) { + t.Parallel() + p := script.Echo("a\nb\nc\n").ExecForEach("{{invalid template syntax}}") + if p.Wait() == nil { + t.Error("want error, got nil") + } +} + +func TestWait_DoesNotReturnErrorForValidExecution(t *testing.T) { + t.Parallel() + p := script.Echo("a\nb\nc\n").ExecForEach("echo \"{{.}}\"") + if err := p.Wait(); err != nil { + t.Fatal(err) + } +} + var base64Cases = []struct { name string decoded string