Skip to content

Commit

Permalink
cmd: Allow caddy fmt to read from stdin (#3680)
Browse files Browse the repository at this point in the history
* Allow 'caddy fmt' to read from stdin

* fmt: use '-' as the file name for reading from stdin

* Minor adjustments

Co-authored-by: Matthew Holt <[email protected]>
  • Loading branch information
matthewpi and mholt authored Sep 14, 2020
1 parent 4217217 commit b88e2b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
17 changes: 13 additions & 4 deletions cmd/commandfuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,17 @@ func cmdFmt(fl Flags) (int, error) {
if formatCmdConfigFile == "" {
formatCmdConfigFile = "Caddyfile"
}
overwrite := fl.Bool("overwrite")

// as a special case, read from stdin if the file name is "-"
if formatCmdConfigFile == "-" {
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return caddy.ExitCodeFailedStartup,
fmt.Errorf("reading stdin: %v", err)
}
fmt.Print(string(caddyfile.Format(input)))
return caddy.ExitCodeSuccess, nil
}

input, err := ioutil.ReadFile(formatCmdConfigFile)
if err != nil {
Expand All @@ -543,9 +553,8 @@ func cmdFmt(fl Flags) (int, error) {

output := caddyfile.Format(input)

if overwrite {
err = ioutil.WriteFile(formatCmdConfigFile, output, 0644)
if err != nil {
if fl.Bool("overwrite") {
if err := ioutil.WriteFile(formatCmdConfigFile, output, 0600); err != nil {
return caddy.ExitCodeFailedStartup, nil
}
} else {
Expand Down
8 changes: 6 additions & 2 deletions cmd/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,12 @@ provisioning stages.`,
Formats the Caddyfile by adding proper indentation and spaces to improve
human readability. It prints the result to stdout.
If --write is specified, the output will be written to the config file
directly instead of printing it.`,
If --overwrite is specified, the output will be written to the config file
directly instead of printing it.
If you wish you use stdin instead of a regular file, use - as the path.
When reading from stdin, the --overwrite flag has no effect: the result
is always printed to stdout.`,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("format", flag.ExitOnError)
fs.Bool("overwrite", false, "Overwrite the input file with the results")
Expand Down

0 comments on commit b88e2b6

Please sign in to comment.