From b3e692ed09f8ba15b741621c4b16d8bfee38f8a1 Mon Sep 17 00:00:00 2001 From: Ted Date: Mon, 17 Mar 2025 17:58:46 +0300 Subject: [PATCH] caddyfile: Fix formatting for backquote wrapped braces (#6903) --- caddyconfig/caddyfile/formatter.go | 17 +++++++++++++++-- caddyconfig/caddyfile/formatter_test.go | 10 ++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/caddyconfig/caddyfile/formatter.go b/caddyconfig/caddyfile/formatter.go index d35f0ac6b..f1d12fa51 100644 --- a/caddyconfig/caddyfile/formatter.go +++ b/caddyconfig/caddyfile/formatter.go @@ -61,7 +61,8 @@ func Format(input []byte) []byte { heredocMarker []rune heredocClosingMarker []rune - nesting int // indentation level + nesting int // indentation level + withinBackquote bool ) write := func(ch rune) { @@ -88,6 +89,9 @@ func Format(input []byte) []byte { } panic(err) } + if ch == '`' { + withinBackquote = !withinBackquote + } // detect whether we have the start of a heredoc if !quoted && !(heredoc != heredocClosed || heredocEscaped) && @@ -236,14 +240,23 @@ func Format(input []byte) []byte { switch { case ch == '{': openBrace = true - openBraceWritten = false openBraceSpace = spacePrior && !beginningOfLine if openBraceSpace { write(' ') } + openBraceWritten = false + if withinBackquote { + write('{') + openBraceWritten = true + continue + } continue case ch == '}' && (spacePrior || !openBrace): + if withinBackquote { + write('}') + continue + } if last != '\n' { nextLine() } diff --git a/caddyconfig/caddyfile/formatter_test.go b/caddyconfig/caddyfile/formatter_test.go index 6eec822fe..a64383c3c 100644 --- a/caddyconfig/caddyfile/formatter_test.go +++ b/caddyconfig/caddyfile/formatter_test.go @@ -434,6 +434,16 @@ block2 { } `, }, + { + description: "Preserve braces wrapped by backquotes", + input: "block {respond `All braces should remain: {{now | date \"2006\"}}`}", + expect: "block {respond `All braces should remain: {{now | date \"2006\"}}`}", + }, + { + description: "Preserve braces wrapped by quotes", + input: "block {respond \"All braces should remain: {{now | date `2006`}}\"}", + expect: "block {respond \"All braces should remain: {{now | date `2006`}}\"}", + }, } { // the formatter should output a trailing newline, // even if the tests aren't written to expect that