diff --git a/.changelog/4020.txt b/.changelog/4020.txt new file mode 100644 index 00000000000..f71623203e4 --- /dev/null +++ b/.changelog/4020.txt @@ -0,0 +1,4 @@ +```release-note:improvement +cli/fmt: Add a `-check` flag that will determine if the `waypoint.hcl` is already +properly formatted, similar to `terraform fmt -check`. +``` diff --git a/internal/cli/fmt.go b/internal/cli/fmt.go index f7aa746aa9c..eb5ac08e63d 100644 --- a/internal/cli/fmt.go +++ b/internal/cli/fmt.go @@ -1,6 +1,7 @@ package cli import ( + "bytes" "fmt" "io/ioutil" "os" @@ -20,6 +21,7 @@ type FmtCommand struct { *baseCommand flagWrite bool + flagCheck bool } func (c *FmtCommand) Run(args []string) int { @@ -70,6 +72,18 @@ func (c *FmtCommand) Run(args []string) int { return 1 } + if c.flagCheck { + // In the case where we're checking formatting, don't persist data + // ultimately this shouldn't even be used because we should return + // in this block + c.flagWrite = false + if bytes.Equal(src, out) { + return 0 + } else { + return 3 + } + } + // If we're writing then write it to the file. stdin never writes to a file if c.flagWrite && !stdin { if err := ioutil.WriteFile(c.args[0], out, 0644); err != nil { @@ -108,7 +122,15 @@ func (c *FmtCommand) Flags() *flag.Sets { Default: true, Usage: "Overwrite the input file. If this is false, the formatted " + "output will be written to STDOUT. This has no effect when formatting " + - "from STDIN.", + "from STDIN or when using the -check flag.", + }) + + f.BoolVar(&flag.BoolVar{ + Name: "check", + Target: &c.flagCheck, + Default: false, + Usage: "Check if the input is formatted. Exit status will be 0 if " + + "all input is properly formatted and exit status 3 otherwise.", }) }) } diff --git a/website/content/commands/fmt.mdx b/website/content/commands/fmt.mdx index 215ec2e3ada..ec35b721a79 100644 --- a/website/content/commands/fmt.mdx +++ b/website/content/commands/fmt.mdx @@ -38,6 +38,7 @@ work for older and newer configuration formats. #### Command Options -- `-write` - Overwrite the input file. If this is false, the formatted output will be written to STDOUT. This has no effect when formatting from STDIN. The default is true. +- `-write` - Overwrite the input file. If this is false, the formatted output will be written to STDOUT. This has no effect when formatting from STDIN or when using the -check flag. The default is true. +- `-check` - Check if the input is formatted. Exit status will be 0 if all input is properly formatted and exit status 3 otherwise. The default is false. @include "commands/fmt_more.mdx"