Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow hcl format from stdin #3288

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
45 changes: 45 additions & 0 deletions cli/commands/hclfmt/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
package hclfmt

import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
Expand All @@ -27,6 +29,16 @@ import (
func Run(opts *options.TerragruntOptions) error {
workingDir := opts.WorkingDir
targetFile := opts.HclFile
stdIn := opts.HclFromStdin

if stdIn {
if targetFile != "" {
opts.Logger.Debugf("Both stdin and path flags are specified")
return fmt.Errorf("both stdin and path flags are specified")
}

return formatFromStdin(opts)
}

// handle when option specifies a particular file
if targetFile != "" {
Expand Down Expand Up @@ -74,6 +86,39 @@ func Run(opts *options.TerragruntOptions) error {
return formatErrors.ErrorOrNil()
}

func formatFromStdin(opts *options.TerragruntOptions) error {

contents, err := io.ReadAll(os.Stdin)

if err != nil {
opts.Logger.Errorf("Error reading from stdin: %s", err)
return err
}

err = checkErrors(opts.Logger, opts.DisableLogColors, contents, "stdin")
if err != nil {
opts.Logger.Errorf("Error parsing hcl from stdin")
return err
}

newContents := hclwrite.Format(contents)

buf := bufio.NewWriter(os.Stdout)
_, err = buf.Write(newContents)
if err != nil {
opts.Logger.Errorf("Failed to write to stdout")
return err
}

err = buf.Flush()
if err != nil {
opts.Logger.Errorf("Failed to flush to stdout")
return err
}

return nil
}

// formatTgHCL uses the hcl2 library to format the hcl file. This will attempt to parse the HCL file first to
// ensure that there are no syntax errors, before attempting to format it.
func formatTgHCL(opts *options.TerragruntOptions, tgHclFile string) error {
Expand Down
32 changes: 32 additions & 0 deletions cli/commands/hclfmt/action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,38 @@ func TestHCLFmtFile(t *testing.T) {
}
}

func TestHCLFmtStdin(t *testing.T) {

realStdin := os.Stdin
realStdout := os.Stdout

tempStdoutFile, err := os.CreateTemp(os.TempDir(), "stdout-*.hcl")
alikhil marked this conversation as resolved.
Show resolved Hide resolved
require.NoError(t, err)
defer os.Remove(tempStdoutFile.Name())
alikhil marked this conversation as resolved.
Show resolved Hide resolved

os.Stdout = tempStdoutFile
defer func() { os.Stdout = realStdout }()

os.Stdin, err = os.Open("../../../test/fixture-hclfmt-stdin/terragrunt.hcl")
defer func() { os.Stdin = realStdin }()
require.NoError(t, err)

expected, err := os.ReadFile("../../../test/fixture-hclfmt-stdin/expected.hcl")
require.NoError(t, err)

tgOptions, err := options.NewTerragruntOptionsForTest("")
require.NoError(t, err)

// format hcl froms tdin
alikhil marked this conversation as resolved.
Show resolved Hide resolved
tgOptions.HclFromStdin = true
err = Run(tgOptions)
require.NoError(t, err)

formatted, err := os.ReadFile(tempStdoutFile.Name())
require.NoError(t, err)
assert.Equal(t, expected, formatted)
}

func TestHCLFmtHeredoc(t *testing.T) {
t.Parallel()

Expand Down
13 changes: 10 additions & 3 deletions cli/commands/hclfmt/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import (
const (
CommandName = "hclfmt"

FlagNameTerragruntHCLFmt = "terragrunt-hclfmt-file"
FlagNameTerragruntCheck = "terragrunt-check"
FlagNameTerragruntDiff = "terragrunt-diff"
FlagNameTerragruntHCLFmt = "terragrunt-hclfmt-file"
FlagNameTerragruntCheck = "terragrunt-check"
FlagNameTerragruntDiff = "terragrunt-diff"
FlagNameTerragruntHCLFmtStdin = "terragrunt-hclfmt-stdin"
)

func NewFlags(opts *options.TerragruntOptions) cli.Flags {
Expand All @@ -32,6 +33,12 @@ func NewFlags(opts *options.TerragruntOptions) cli.Flags {
EnvVar: "TERRAGRUNT_DIFF",
Usage: "Print diff between original and modified file versions when running with 'hclfmt'.",
},
&cli.BoolFlag{
Name: FlagNameTerragruntHCLFmtStdin,
Destination: &opts.HclFromStdin,
EnvVar: "TERRAGRUNT_HCLFMT_STDIN",
Usage: "Format HCL from stdin and print result to stdout.",
},
}
}

Expand Down
12 changes: 11 additions & 1 deletion docs/_docs/04_reference/cli-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ This page documents the CLI commands and options available with Terragrunt:
- [terragrunt-check](#terragrunt-check)
- [terragrunt-diff](#terragrunt-diff)
- [terragrunt-hclfmt-file](#terragrunt-hclfmt-file)
- [terragrunt-hclfmt-stdin](#terragrunt-hclfmt-stdin)
- [terragrunt-hclvalidate-json](#terragrunt-hclvalidate-json)
- [terragrunt-hclvalidate-invalid](#terragrunt-hclvalidate-invalid)
- [terragrunt-override-attr](#terragrunt-override-attr)
Expand Down Expand Up @@ -763,6 +764,7 @@ prefix `--terragrunt-` (e.g., `--terragrunt-config`). The currently available op
- [terragrunt-check](#terragrunt-check)
- [terragrunt-diff](#terragrunt-diff)
- [terragrunt-hclfmt-file](#terragrunt-hclfmt-file)
- [terragrunt-hclfmt-stdin](#terragrunt-hclfmt-stdin)
- [terragrunt-hclvalidate-json](#terragrunt-hclvalidate-json)
- [terragrunt-hclvalidate-invalid](#terragrunt-hclvalidate-invalid)
- [terragrunt-override-attr](#terragrunt-override-attr)
Expand Down Expand Up @@ -1118,7 +1120,15 @@ When passed in, running `hclfmt` will print diff between original and modified f

- [hclfmt](#hclfmt)

When passed in, run `hclfmt` only on specified hcl file.
### terragrunt-hclfmt-stdin

**CLI Arg**: `--terragrunt-hclfmt-stdin`<br/>
**Environment Variable**: `TERRAGRUNT_HCLFMT_STDIN` (set to `true`)<br/>
**Commands**:

- [hclfmt](#hclfmt)

When passed in, run `hclfmt` only on hcl passed to `stdin`, result is printed to `stdout`.

### terragrunt-hclvalidate-json

Expand Down
3 changes: 3 additions & 0 deletions options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ type TerragruntOptions struct {
// The file which hclfmt should be specifically run on
HclFile string

// If True then HCL from StdIn must should be formatted.
HclFromStdin bool

// The file path that terragrunt should use when rendering the terragrunt.hcl config as json.
JSONOut string

Expand Down
13 changes: 13 additions & 0 deletions test/fixture-hclfmt-stdin/expected.hcl
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
inputs = {
# comments
foo = "bar"
bar = "baz"

inputs = "disjoint"
disjoint = true

listInput = [
"foo",
"bar",
]
}
13 changes: 13 additions & 0 deletions test/fixture-hclfmt-stdin/terragrunt.hcl
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
inputs = {
# comments
foo = "bar"
bar="baz"

inputs = "disjoint"
disjoint = true

listInput = [
"foo",
"bar",
]
}