| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package yaml |
| 5 |
|
| 6 |
import ( |
| 7 |
"strings" |
| 8 |
) |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
func DeriveSeqIndentStyle(originalYAML string) string { |
| 14 |
lines := strings.Split(originalYAML, "\n") |
| 15 |
for i, line := range lines { |
| 16 |
elems := strings.SplitN(line, "- ", 2) |
| 17 |
if len(elems) != 2 { |
| 18 |
continue |
| 19 |
} |
| 20 |
|
| 21 |
if strings.Trim(elems[0], " ") != "" { |
| 22 |
continue |
| 23 |
} |
| 24 |
numSpacesBeforeSeqElem := len(elems[0]) |
| 25 |
|
| 26 |
|
| 27 |
keyLine := keyLineBeforeSeqElem(lines, i) |
| 28 |
if keyLine == "" { |
| 29 |
|
| 30 |
|
| 31 |
continue |
| 32 |
} |
| 33 |
numSpacesBeforeKeyElem := len(keyLine) - len(strings.TrimLeft(keyLine, " ")) |
| 34 |
trimmedKeyLine := strings.Trim(keyLine, " ") |
| 35 |
if strings.Count(trimmedKeyLine, ":") != 1 || !strings.HasSuffix(trimmedKeyLine, ":") { |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
continue |
| 40 |
} |
| 41 |
|
| 42 |
if numSpacesBeforeSeqElem == numSpacesBeforeKeyElem { |
| 43 |
return string(CompactSequenceStyle) |
| 44 |
} |
| 45 |
|
| 46 |
if numSpacesBeforeSeqElem-numSpacesBeforeKeyElem == 2 { |
| 47 |
return string(WideSequenceStyle) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
return string(CompactSequenceStyle) |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
func keyLineBeforeSeqElem(lines []string, seqElemIndex int) string { |
| 57 |
|
| 58 |
i := seqElemIndex - 1 |
| 59 |
for ; i >= 0; i-- { |
| 60 |
line := lines[i] |
| 61 |
trimmedLine := strings.Trim(line, " ") |
| 62 |
if strings.HasPrefix(trimmedLine, "#") { |
| 63 |
continue |
| 64 |
} |
| 65 |
|
| 66 |
parts := strings.SplitN(line, "#", 2) |
| 67 |
return parts[0] |
| 68 |
} |
| 69 |
return "" |
| 70 |
} |