Skip to content

Commit 6faca8b

Browse files
committed
reinstate error wrapping for context errs
1 parent 0934b50 commit 6faca8b

File tree

3 files changed

+46
-9
lines changed

3 files changed

+46
-9
lines changed

tfexec/cmd_default.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
4040
}
4141

4242
err = cmd.Start()
43-
if err == nil && ctx.Err() != nil {
44-
err = ctx.Err()
43+
if ctx.Err() != nil {
44+
return cmdErr{
45+
err: err,
46+
ctxErr: ctx.Err(),
47+
}
4548
}
4649
if err != nil {
4750
return err
@@ -66,8 +69,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
6669
wg.Wait()
6770

6871
err = cmd.Wait()
69-
if err == nil && ctx.Err() != nil {
70-
err = ctx.Err()
72+
if ctx.Err() != nil {
73+
return cmdErr{
74+
err: err,
75+
ctxErr: ctx.Err(),
76+
}
7177
}
7278
if err != nil {
7379
return err

tfexec/cmd_linux.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
4545
}
4646

4747
err = cmd.Start()
48-
if err == nil && ctx.Err() != nil {
49-
err = ctx.Err()
48+
if ctx.Err() != nil {
49+
return cmdErr{
50+
err: err,
51+
ctxErr: ctx.Err(),
52+
}
5053
}
5154
if err != nil {
5255
return err
@@ -71,8 +74,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
7174
wg.Wait()
7275

7376
err = cmd.Wait()
74-
if err == nil && ctx.Err() != nil {
75-
err = ctx.Err()
77+
if ctx.Err() != nil {
78+
return cmdErr{
79+
err: err,
80+
ctxErr: ctx.Err(),
81+
}
7682
}
7783
if err != nil {
7884
return err

tfexec/errors.go

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package tfexec
22

3-
import "fmt"
3+
import (
4+
"context"
5+
"fmt"
6+
)
47

58
// this file contains non-parsed exported errors
69

@@ -37,3 +40,25 @@ type ErrManualEnvVar struct {
3740
func (err *ErrManualEnvVar) Error() string {
3841
return fmt.Sprintf("manual setting of env var %q detected", err.Name)
3942
}
43+
44+
// cmdErr is a custom error type to be returned when a cmd exits with a context
45+
// error such as context.Canceled or context.DeadlineExceeded.
46+
// The type is specifically designed to respond true to errors.Is for these two
47+
// errors.
48+
// See https://github.com/golang/go/issues/21880 for why this is necessary.
49+
type cmdErr struct {
50+
err error
51+
ctxErr error
52+
}
53+
54+
func (e cmdErr) Is(target error) bool {
55+
switch target {
56+
case context.DeadlineExceeded, context.Canceled:
57+
return e.ctxErr == context.DeadlineExceeded || e.ctxErr == context.Canceled
58+
}
59+
return false
60+
}
61+
62+
func (e cmdErr) Error() string {
63+
return e.err.Error()
64+
}

0 commit comments

Comments
 (0)