From b88e2b6a497789307b0a12f9867cf2ac8088d73a Mon Sep 17 00:00:00 2001 From: Matthew Penner Date: Mon, 14 Sep 2020 12:30:12 -0600 Subject: cmd: Allow `caddy fmt` to read from stdin (#3680) * Allow 'caddy fmt' to read from stdin * fmt: use '-' as the file name for reading from stdin * Minor adjustments Co-authored-by: Matthew Holt --- cmd/commandfuncs.go | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'cmd/commandfuncs.go') diff --git a/cmd/commandfuncs.go b/cmd/commandfuncs.go index a10bc19..772fe01 100644 --- a/cmd/commandfuncs.go +++ b/cmd/commandfuncs.go @@ -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 { @@ -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 { -- cgit v1.2.3