Browse Source

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 <mholt@users.noreply.github.com>
master
Matthew Penner 4 years ago
committed by GitHub
parent
commit
b88e2b6a49
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 17
      cmd/commandfuncs.go
  2. 8
      cmd/commands.go

17
cmd/commandfuncs.go

@ -533,7 +533,17 @@ func cmdFmt(fl Flags) (int, error) {
if formatCmdConfigFile == "" { if formatCmdConfigFile == "" {
formatCmdConfigFile = "Caddyfile" 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) input, err := ioutil.ReadFile(formatCmdConfigFile)
if err != nil { if err != nil {
@ -543,9 +553,8 @@ func cmdFmt(fl Flags) (int, error) {
output := caddyfile.Format(input) output := caddyfile.Format(input)
if overwrite { if fl.Bool("overwrite") {
err = ioutil.WriteFile(formatCmdConfigFile, output, 0644) if err := ioutil.WriteFile(formatCmdConfigFile, output, 0600); err != nil {
if err != nil {
return caddy.ExitCodeFailedStartup, nil return caddy.ExitCodeFailedStartup, nil
} }
} else { } else {

8
cmd/commands.go

@ -263,8 +263,12 @@ provisioning stages.`,
Formats the Caddyfile by adding proper indentation and spaces to improve Formats the Caddyfile by adding proper indentation and spaces to improve
human readability. It prints the result to stdout. human readability. It prints the result to stdout.
If --write is specified, the output will be written to the config file If --overwrite is specified, the output will be written to the config file
directly instead of printing it.`, 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 { Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("format", flag.ExitOnError) fs := flag.NewFlagSet("format", flag.ExitOnError)
fs.Bool("overwrite", false, "Overwrite the input file with the results") fs.Bool("overwrite", false, "Overwrite the input file with the results")

Loading…
Cancel
Save