cmd: caddy fmt return code is 1 if not formatted (#5297)

* cmd: Fix caddy fmt if input isn't formatted

* Fixes #5294
* return exit 1 with an error message

* cmd: Use formattingDifference for caddy fmt

* #5294
* expose caddyfile.formattingDifference
This commit is contained in:
Y.Horie 2023-01-22 13:28:37 +09:00 committed by GitHub
parent d6d7511699
commit 5805b3ca11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 3 deletions

View File

@ -54,7 +54,7 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
// lint check: see if input was properly formatted; sometimes messy files files parse // lint check: see if input was properly formatted; sometimes messy files files parse
// successfully but result in logical errors (the Caddyfile is a bad format, I'm sorry) // successfully but result in logical errors (the Caddyfile is a bad format, I'm sorry)
if warning, different := formattingDifference(filename, body); different { if warning, different := FormattingDifference(filename, body); different {
warnings = append(warnings, warning) warnings = append(warnings, warning)
} }
@ -63,10 +63,10 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
return result, warnings, err return result, warnings, err
} }
// formattingDifference returns a warning and true if the formatted version // FormattingDifference returns a warning and true if the formatted version
// is any different from the input; empty warning and false otherwise. // is any different from the input; empty warning and false otherwise.
// TODO: also perform this check on imported files // TODO: also perform this check on imported files
func formattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) { func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) {
// replace windows-style newlines to normalize comparison // replace windows-style newlines to normalize comparison
normalizedBody := bytes.Replace(body, []byte("\r\n"), []byte("\n"), -1) normalizedBody := bytes.Replace(body, []byte("\r\n"), []byte("\n"), -1)

View File

@ -576,6 +576,10 @@ func cmdFmt(fl Flags) (int, error) {
fmt.Print(string(output)) fmt.Print(string(output))
} }
if warning, diff := caddyfile.FormattingDifference(formatCmdConfigFile, input); diff {
return caddy.ExitCodeFailedStartup, fmt.Errorf("%s:%d: Caddyfile input is not formatted", warning.File, warning.Line)
}
return caddy.ExitCodeSuccess, nil return caddy.ExitCodeSuccess, nil
} }