Skip to content
This repository has been archived by the owner on Jan 8, 2024. It is now read-only.

add -check flag to fmt #4020

Merged
merged 4 commits into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changelog/4020.txt
Original file line number Diff line number Diff line change
@@ -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`.
```
24 changes: 23 additions & 1 deletion internal/cli/fmt.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"bytes"
"fmt"
"io/ioutil"
"os"
Expand All @@ -20,6 +21,7 @@ type FmtCommand struct {
*baseCommand

flagWrite bool
flagCheck bool
}

func (c *FmtCommand) Run(args []string) int {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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.",
})
})
}
Expand Down
3 changes: 2 additions & 1 deletion website/content/commands/fmt.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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"