Skip to content

Commit

Permalink
reinstate error wrapping for context errs
Browse files Browse the repository at this point in the history
  • Loading branch information
kmoe committed Feb 14, 2023
1 parent 0934b50 commit 6faca8b
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 9 deletions.
14 changes: 10 additions & 4 deletions tfexec/cmd_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
}

err = cmd.Start()
if err == nil && ctx.Err() != nil {
err = ctx.Err()
if ctx.Err() != nil {
return cmdErr{
err: err,
ctxErr: ctx.Err(),
}
}
if err != nil {
return err
Expand All @@ -66,8 +69,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
wg.Wait()

err = cmd.Wait()
if err == nil && ctx.Err() != nil {
err = ctx.Err()
if ctx.Err() != nil {
return cmdErr{
err: err,
ctxErr: ctx.Err(),
}
}
if err != nil {
return err
Expand Down
14 changes: 10 additions & 4 deletions tfexec/cmd_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
}

err = cmd.Start()
if err == nil && ctx.Err() != nil {
err = ctx.Err()
if ctx.Err() != nil {
return cmdErr{
err: err,
ctxErr: ctx.Err(),
}
}
if err != nil {
return err
Expand All @@ -71,8 +74,11 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
wg.Wait()

err = cmd.Wait()
if err == nil && ctx.Err() != nil {
err = ctx.Err()
if ctx.Err() != nil {
return cmdErr{
err: err,
ctxErr: ctx.Err(),
}
}
if err != nil {
return err
Expand Down
27 changes: 26 additions & 1 deletion tfexec/errors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package tfexec

import "fmt"
import (
"context"
"fmt"
)

// this file contains non-parsed exported errors

Expand Down Expand Up @@ -37,3 +40,25 @@ type ErrManualEnvVar struct {
func (err *ErrManualEnvVar) Error() string {
return fmt.Sprintf("manual setting of env var %q detected", err.Name)
}

// cmdErr is a custom error type to be returned when a cmd exits with a context
// error such as context.Canceled or context.DeadlineExceeded.
// The type is specifically designed to respond true to errors.Is for these two
// errors.
// See https://github.com/golang/go/issues/21880 for why this is necessary.
type cmdErr struct {
err error
ctxErr error
}

func (e cmdErr) Is(target error) bool {
switch target {
case context.DeadlineExceeded, context.Canceled:
return e.ctxErr == context.DeadlineExceeded || e.ctxErr == context.Canceled
}
return false
}

func (e cmdErr) Error() string {
return e.err.Error()
}

0 comments on commit 6faca8b

Please sign in to comment.