Skip to content

Commit 55a3639

Browse files
committed
(Re)Implement QueryJSON as LogMsg emitter
1 parent 061a850 commit 55a3639

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

tfexec/query.go

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44
package tfexec
55

66
import (
7+
"bufio"
78
"context"
89
"fmt"
910
"io"
1011
"os/exec"
12+
13+
tfjson "github.com/hashicorp/terraform-json"
1114
)
1215

1316
type queryConfig struct {
@@ -57,25 +60,42 @@ func (opt *VarOption) configureQuery(conf *queryConfig) {
5760
//
5861
// QueryJSON is likely to be removed in a future major version in favour of
5962
// query returning JSON by default.
60-
func (tf *Terraform) QueryJSON(ctx context.Context, w io.Writer, opts ...QueryOption) error {
63+
func (tf *Terraform) QueryJSON(ctx context.Context, opts ...QueryOption) (*LogMsgEmitter, error) {
6164
err := tf.compatible(ctx, tf1_14_0, nil)
6265
if err != nil {
63-
return fmt.Errorf("terraform query -json was added in 1.14.0: %w", err)
66+
return nil, fmt.Errorf("terraform query -json was added in 1.14.0: %w", err)
6467
}
6568

66-
tf.SetStdout(w)
69+
pr, pw := io.Pipe()
70+
defer pw.Close()
71+
defer pr.Close()
72+
tf.SetStdout(pw)
6773

6874
cmd, err := tf.queryJSONCmd(ctx, opts...)
6975
if err != nil {
70-
return err
76+
return nil, err
7177
}
7278

7379
err = tf.runTerraformCmd(ctx, cmd)
7480
if err != nil {
75-
return err
81+
return nil, err
7682
}
7783

78-
return nil
84+
return &LogMsgEmitter{
85+
r: bufio.NewReader(pr),
86+
}, nil
87+
}
88+
89+
type LogMsgEmitter struct {
90+
r *bufio.Reader
91+
}
92+
93+
func (e *LogMsgEmitter) NextMessage() (tfjson.LogMsg, error) {
94+
rawMessage, err := e.r.ReadBytes('\n')
95+
if err != nil {
96+
return nil, err
97+
}
98+
return tfjson.UnmarshalLogMessage(rawMessage)
7999
}
80100

81101
func (tf *Terraform) queryJSONCmd(ctx context.Context, opts ...QueryOption) (*exec.Cmd, error) {

0 commit comments

Comments
 (0)