|
4 | 4 | package tfexec
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "bufio" |
7 | 8 | "context"
|
8 | 9 | "fmt"
|
9 | 10 | "io"
|
10 | 11 | "os/exec"
|
| 12 | + |
| 13 | + tfjson "github.com/hashicorp/terraform-json" |
11 | 14 | )
|
12 | 15 |
|
13 | 16 | type queryConfig struct {
|
@@ -57,25 +60,42 @@ func (opt *VarOption) configureQuery(conf *queryConfig) {
|
57 | 60 | //
|
58 | 61 | // QueryJSON is likely to be removed in a future major version in favour of
|
59 | 62 | // 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) { |
61 | 64 | err := tf.compatible(ctx, tf1_14_0, nil)
|
62 | 65 | 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) |
64 | 67 | }
|
65 | 68 |
|
66 |
| - tf.SetStdout(w) |
| 69 | + pr, pw := io.Pipe() |
| 70 | + defer pw.Close() |
| 71 | + defer pr.Close() |
| 72 | + tf.SetStdout(pw) |
67 | 73 |
|
68 | 74 | cmd, err := tf.queryJSONCmd(ctx, opts...)
|
69 | 75 | if err != nil {
|
70 |
| - return err |
| 76 | + return nil, err |
71 | 77 | }
|
72 | 78 |
|
73 | 79 | err = tf.runTerraformCmd(ctx, cmd)
|
74 | 80 | if err != nil {
|
75 |
| - return err |
| 81 | + return nil, err |
76 | 82 | }
|
77 | 83 |
|
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) |
79 | 99 | }
|
80 | 100 |
|
81 | 101 | func (tf *Terraform) queryJSONCmd(ctx context.Context, opts ...QueryOption) (*exec.Cmd, error) {
|
|
0 commit comments