Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions caddyconfig/caddyfile/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,10 @@ func Format(input []byte) []byte {
heredocMarker []rune
heredocClosingMarker []rune

nesting int // indentation level
withinBackquote bool
nesting int // indentation level
withinBacktick bool
afterQuotedBacktick bool // after "`
afterBacktickedQuote bool // after `"
)

write := func(ch rune) {
Expand All @@ -89,10 +91,6 @@ 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) &&
space && last == '<' && ch == '<' {
Expand Down Expand Up @@ -180,14 +178,41 @@ func Format(input []byte) []byte {
continue
}

if ch == '`' {
if afterQuotedBacktick {
afterBacktickedQuote = false
withinBacktick = false
} else if withinBacktick {
withinBacktick = false
} else if quoted {
afterQuotedBacktick = true
withinBacktick = true
} else {
withinBacktick = true
}
}

if quoted {
if ch == '"' {
if afterQuotedBacktick {
withinBacktick = false
}
afterQuotedBacktick = false
quoted = false
}
write(ch)
continue
}

if ch == '"' && afterQuotedBacktick {
withinBacktick = false
afterQuotedBacktick = false
}
if ch == '"' && afterBacktickedQuote {
withinBacktick = false
afterBacktickedQuote = false
}

if space && ch == '"' {
quoted = true
}
Expand Down Expand Up @@ -245,15 +270,15 @@ func Format(input []byte) []byte {
write(' ')
}
openBraceWritten = false
if withinBackquote {
if withinBacktick && !afterQuotedBacktick && !afterBacktickedQuote {
write('{')
openBraceWritten = true
continue
}
continue

case ch == '}' && (spacePrior || !openBrace):
if withinBackquote {
if withinBacktick && !afterQuotedBacktick && !afterBacktickedQuote {
write('}')
continue
}
Expand Down
5 changes: 5 additions & 0 deletions caddyconfig/caddyfile/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,11 @@ block2 {
input: "block {respond \"All braces should remain: {{now | date `2006`}}\"}",
expect: "block {respond \"All braces should remain: {{now | date `2006`}}\"}",
},
{
description: "Preserve quoted backticks and backticked quotes",
input: "block { respond \"`\" } block { respond `\"`}",
expect: "block {\n\trespond \"`\"\n}\n\nblock {\n\trespond `\"`\n}",
},
} {
// the formatter should output a trailing newline,
// even if the tests aren't written to expect that
Expand Down
Loading