From 160d19999982c4facd32c4bddced5a7dc91e8a40 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Tue, 19 Jan 2021 14:21:11 -0700 Subject: caddytest: Update Caddyfile tests for formatting, HTTP-only blocks Previous commit improved the Caddyfile adapter so it doesn't unnecessarily add names to "skip" in "auto_https" when the server is already HTTP-only. This commit updates the tests to reflect that change, while also fixing the Caddyfile formatting in many of the tests. We also print the line number of the divergence between input and formatted version in Caddyfile adapt warnings - very useful for finding initial formatting problems. --- caddyconfig/caddyfile/adapter.go | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) (limited to 'caddyconfig/caddyfile') diff --git a/caddyconfig/caddyfile/adapter.go b/caddyconfig/caddyfile/adapter.go index 185816b..7f5ebc5 100644 --- a/caddyconfig/caddyfile/adapter.go +++ b/caddyconfig/caddyfile/adapter.go @@ -53,13 +53,9 @@ func (a Adapter) Adapt(body []byte, options map[string]interface{}) ([]byte, []c } // lint check: see if input was properly formatted; sometimes messy files files parse - // successfully but result in logical errors because the Caddyfile is a bad format - // TODO: also perform this check on imported files - if !bytes.Equal(Format(body), body) { - warnings = append(warnings, caddyconfig.Warning{ - File: filename, - Message: "file is not formatted with 'caddy fmt'", - }) + // successfully but result in logical errors (the Caddyfile is a bad format, I'm sorry) + if warning, different := formattingDifference(filename, body); different { + warnings = append(warnings, warning) } result, err := json.Marshal(cfg) @@ -67,6 +63,32 @@ func (a Adapter) Adapt(body []byte, options map[string]interface{}) ([]byte, []c return result, warnings, err } +// formattingDifference returns a warning and true if the formatted version +// is any different from the input; empty warning and false otherwise. +// TODO: also perform this check on imported files +func formattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) { + formatted := Format(body) + if bytes.Equal(formatted, body) { + return caddyconfig.Warning{}, false + } + + // find where the difference is + line := 1 + for i, ch := range body { + if i >= len(formatted) || ch != formatted[i] { + break + } + if ch == '\n' { + line++ + } + } + return caddyconfig.Warning{ + File: filename, + Line: line, + Message: "input is not formatted with 'caddy fmt'", + }, true +} + // Unmarshaler is a type that can unmarshal // Caddyfile tokens to set itself up for a // JSON encoding. The goal of an unmarshaler -- cgit v1.2.3