Format formats the input Caddyfile to a standard, nice-looking appearance. It works by reading each rune of the input and taking control over all the bracing and whitespace that is written; otherwise, words, comments, placeholders, and escaped characters are all treated literally and written as they
(input []byte)
| 28 | // words, comments, placeholders, and escaped characters are all treated |
| 29 | // literally and written as they appear in the input. |
| 30 | func Format(input []byte) []byte { |
| 31 | input = bytes.TrimSpace(input) |
| 32 | |
| 33 | out := new(bytes.Buffer) |
| 34 | rdr := bytes.NewReader(input) |
| 35 | |
| 36 | type heredocState int |
| 37 | |
| 38 | const ( |
| 39 | heredocClosed heredocState = 0 |
| 40 | heredocOpening heredocState = 1 |
| 41 | heredocOpened heredocState = 2 |
| 42 | ) |
| 43 | |
| 44 | var ( |
| 45 | last rune // the last character that was written to the result |
| 46 | |
| 47 | space = true // whether current/previous character was whitespace (beginning of input counts as space) |
| 48 | beginningOfLine = true // whether we are at beginning of line |
| 49 | |
| 50 | openBrace bool // whether current word/token is or started with open curly brace |
| 51 | openBraceWritten bool // if openBrace, whether that brace was written or not |
| 52 | openBraceSpace bool // whether there was a non-newline space before open brace |
| 53 | |
| 54 | newLines int // count of newlines consumed |
| 55 | |
| 56 | comment bool // whether we're in a comment |
| 57 | quotes string // encountered quotes ('', '`', '"', '"`', '`"') |
| 58 | escaped bool // whether current char is escaped |
| 59 | |
| 60 | heredoc heredocState // whether we're in a heredoc |
| 61 | heredocEscaped bool // whether heredoc is escaped |
| 62 | heredocMarker []rune |
| 63 | heredocClosingMarker []rune |
| 64 | |
| 65 | nesting int // indentation level |
| 66 | |
| 67 | currentToken strings.Builder |
| 68 | currentLineFirstToken string |
| 69 | previousLineWasTopLevelImport bool |
| 70 | openBraceOwnLine bool |
| 71 | ) |
| 72 | |
| 73 | finishToken := func() { |
| 74 | if currentToken.Len() == 0 { |
| 75 | return |
| 76 | } |
| 77 | if currentLineFirstToken == "" { |
| 78 | currentLineFirstToken = currentToken.String() |
| 79 | } |
| 80 | currentToken.Reset() |
| 81 | } |
| 82 | |
| 83 | finishLine := func() { |
| 84 | finishToken() |
| 85 | if currentLineFirstToken != "" { |
| 86 | previousLineWasTopLevelImport = nesting == 0 && currentLineFirstToken == "import" |
| 87 | } else if !openBrace || !openBraceOwnLine || openBraceWritten { |