Skip to content

Commit

Permalink
Refactor runTerraformCmd
Browse files Browse the repository at this point in the history
 - Use waitgroups for more readability
 - Improve handling errors from writeOutput

Resolves a test error: `read |0: file already closed`
  • Loading branch information
lornasong committed May 20, 2022
1 parent 11f14d2 commit d6a9ddc
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions tfexec/cmd_default.go
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"os/exec"
"strings"
"sync"
)

func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
Expand Down Expand Up @@ -46,13 +47,17 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
return tf.wrapExitError(ctx, err, "")
}

exitChLen := 2
exitCh := make(chan error, exitChLen)
var errStdout, errStderr error
var wg sync.WaitGroup
wg.Add(2)
go func() {
exitCh <- writeOutput(stdoutPipe, stdoutWriter)
errStdout = writeOutput(stdoutPipe, stdoutWriter)
wg.Done()
}()

go func() {
exitCh <- writeOutput(stderrPipe, stderrWriter)
errStderr = writeOutput(stderrPipe, stderrWriter)
wg.Done()
}()

err = cmd.Wait()
Expand All @@ -63,16 +68,16 @@ func (tf *Terraform) runTerraformCmd(ctx context.Context, cmd *exec.Cmd) error {
return tf.wrapExitError(ctx, err, errBuf.String())
}

// Wait for the logs to finish writing
counter := 0
for {
counter++
err := <-exitCh
if err != nil && err != context.Canceled {
return tf.wrapExitError(ctx, err, errBuf.String())
}
if counter >= exitChLen {
return ctx.Err()
}
// Ensure that outputs are done writing after Wait to be safe
wg.Wait()

// Return error if there was an issue reading the std out/err
if errStdout != nil && ctx.Err() != nil {
return tf.wrapExitError(ctx, errStdout, errBuf.String())
}
if errStderr != nil && ctx.Err() != nil {
return tf.wrapExitError(ctx, errStderr, errBuf.String())
}

return nil
}

0 comments on commit d6a9ddc

Please sign in to comment.