0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-30 22:34:15 -05:00

cmd: fmt: Fix brace opening block indentation (#3153)

This fixes indentation for blocks starting with
a brace as:
```Caddyfile
{
    ...
}
```

Fixes #3144

Signed-off-by: Vaibhav <vrongmeal@gmail.com>
This commit is contained in:
Vaibhav 2020-03-17 21:25:36 +05:30 committed by GitHub
parent b62f8e0582
commit f192ae5ea5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 6 deletions

View file

@ -43,6 +43,12 @@ func Format(body []byte) []byte {
err error err error
) )
insertTabs := func(num int) {
for tabs := num; tabs > 0; tabs-- {
result.WriteRune('\t')
}
}
for { for {
prev = curr prev = curr
curr = next curr = next
@ -102,7 +108,7 @@ func Format(body []byte) []byte {
if unicode.IsSpace(next) { if unicode.IsSpace(next) {
indentation++ indentation++
if !unicode.IsSpace(prev) { if !unicode.IsSpace(prev) && !lineBegin {
result.WriteRune(' ') result.WriteRune(' ')
} }
} else { } else {
@ -114,10 +120,12 @@ func Format(body []byte) []byte {
continue continue
} else { } else {
lineBegin = false lineBegin = false
if indentation > 0 { if curr == '{' && unicode.IsSpace(next) {
for tabs := indentation; tabs > 0; tabs-- { // If the block is global, i.e., starts with '{'
result.WriteRune('\t') // One less indentation for these blocks.
} insertTabs(indentation - 1)
} else {
insertTabs(indentation)
} }
} }
} else { } else {

View file

@ -45,6 +45,18 @@ m {
n { o n { o
} }
} }
{
p
}
{ q
}
{
{ r
}
}
`) `)
expected := []byte(` expected := []byte(`
a a
@ -75,6 +87,20 @@ m {
o o
} }
} }
{
p
}
{
q
}
{
{
r
}
}
`) `)
testFormat(t, input, expected) testFormat(t, input, expected)
} }
@ -110,6 +136,9 @@ b {
d { {$E} d { {$E}
} }
{ {$F}
}
`) `)
expected := []byte(` expected := []byte(`
{$A} {$A}
@ -121,6 +150,10 @@ b {
d { d {
{$E} {$E}
} }
{
{$F}
}
`) `)
testFormat(t, input, expected) testFormat(t, input, expected)
} }
@ -190,6 +223,6 @@ g {
func testFormat(t *testing.T, input, expected []byte) { func testFormat(t *testing.T, input, expected []byte) {
output := Format(input) output := Format(input)
if string(output) != string(expected) { if string(output) != string(expected) {
t.Errorf("Expected:\n%s\ngot:\n%s", string(output), string(expected)) t.Errorf("Expected:\n%s\ngot:\n%s", string(expected), string(output))
} }
} }