Skip to content

Commit d6a9ddc

Browse files
committed
Refactor runTerraformCmd
- Use waitgroups for more readability - Improve handling errors from writeOutput Resolves a test error: `read |0: file already closed`
1 parent 11f14d2 commit d6a9ddc

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

tfexec/cmd_default.go

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"context"
88
"os/exec"
99
"strings"
10+
"sync"
1011
)
1112

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

49-
exitChLen := 2
50-
exitCh := make(chan error, exitChLen)
50+
var errStdout, errStderr error
51+
var wg sync.WaitGroup
52+
wg.Add(2)
5153
go func() {
52-
exitCh <- writeOutput(stdoutPipe, stdoutWriter)
54+
errStdout = writeOutput(stdoutPipe, stdoutWriter)
55+
wg.Done()
5356
}()
57+
5458
go func() {
55-
exitCh <- writeOutput(stderrPipe, stderrWriter)
59+
errStderr = writeOutput(stderrPipe, stderrWriter)
60+
wg.Done()
5661
}()
5762

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

66-
// Wait for the logs to finish writing
67-
counter := 0
68-
for {
69-
counter++
70-
err := <-exitCh
71-
if err != nil && err != context.Canceled {
72-
return tf.wrapExitError(ctx, err, errBuf.String())
73-
}
74-
if counter >= exitChLen {
75-
return ctx.Err()
76-
}
71+
// Ensure that outputs are done writing after Wait to be safe
72+
wg.Wait()
73+
74+
// Return error if there was an issue reading the std out/err
75+
if errStdout != nil && ctx.Err() != nil {
76+
return tf.wrapExitError(ctx, errStdout, errBuf.String())
7777
}
78+
if errStderr != nil && ctx.Err() != nil {
79+
return tf.wrapExitError(ctx, errStderr, errBuf.String())
80+
}
81+
82+
return nil
7883
}

0 commit comments

Comments
 (0)