From 71e81d262bc34545f73f1380bc5d078d83d1570f Mon Sep 17 00:00:00 2001
From: Vaibhav <vrongmeal@gmail.com>
Date: Sun, 1 Mar 2020 01:53:08 +0530
Subject: [PATCH] fmt: Add support for block nesting. (#3105)

Previously the formatter did not include support for
blocks inside other blocks. Hence the formatter could
not indent some files properly. This fixes it.

Fixes #3104

Signed-off-by: Vaibhav <vrongmeal@gmail.com>
---
 caddyconfig/caddyfile/formatter.go      | 15 ++++++-----
 caddyconfig/caddyfile/formatter_test.go | 34 +++++++++++++++++++++++++
 2 files changed, 43 insertions(+), 6 deletions(-)

diff --git a/caddyconfig/caddyfile/formatter.go b/caddyconfig/caddyfile/formatter.go
index 6cfb1b269..e93720850 100644
--- a/caddyconfig/caddyfile/formatter.go
+++ b/caddyconfig/caddyfile/formatter.go
@@ -29,12 +29,13 @@ func Format(body []byte) []byte {
 		commented,
 		quoted,
 		escaped,
-		block,
 		environ,
 		lineBegin bool
 
 		firstIteration = true
 
+		indentation = 0
+
 		prev,
 		curr,
 		next rune
@@ -93,13 +94,13 @@ func Format(body []byte) []byte {
 			if curr == '}' {
 				if environ {
 					environ = false
-				} else if block {
-					block = false
+				} else if indentation > 0 {
+					indentation--
 				}
 			}
 			if curr == '{' {
 				if unicode.IsSpace(next) {
-					block = true
+					indentation++
 
 					if !unicode.IsSpace(prev) {
 						result.WriteRune(' ')
@@ -113,8 +114,10 @@ func Format(body []byte) []byte {
 					continue
 				} else {
 					lineBegin = false
-					if block {
-						result.WriteRune('\t')
+					if indentation > 0 {
+						for tabs := indentation; tabs > 0; tabs-- {
+							result.WriteRune('\t')
+						}
 					}
 				}
 			} else {
diff --git a/caddyconfig/caddyfile/formatter_test.go b/caddyconfig/caddyfile/formatter_test.go
index a78ec7c3d..76eca00cd 100644
--- a/caddyconfig/caddyfile/formatter_test.go
+++ b/caddyconfig/caddyfile/formatter_test.go
@@ -29,6 +29,22 @@ b
 
 e { f
 }
+
+g {
+h {
+i
+}
+}
+
+j { k {
+l
+}
+}
+
+m {
+	n { o
+	}
+}
 `)
 	expected := []byte(`
 a
@@ -41,6 +57,24 @@ c {
 e {
 	f
 }
+
+g {
+	h {
+		i
+	}
+}
+
+j {
+	k {
+		l
+	}
+}
+
+m {
+	n {
+		o
+	}
+}
 `)
 	testFormat(t, input, expected)
 }