mirror of
https://github.com/kubernetes-sigs/kustomize.git
synced 2026-05-17 18:25:26 +00:00
Handle comments for seq indent derivation (#4064)
* Handle comments for seq indent derivation * Suggested changes
This commit is contained in:
@@ -20,13 +20,13 @@ func DeriveSeqIndentStyle(originalYAML string) string {
|
||||
}
|
||||
numSpacesBeforeSeqElem := len(elems[0])
|
||||
|
||||
if i == 0 {
|
||||
// keyLine is the line before the first sequence element
|
||||
keyLine := keyLineBeforeSeqElem(lines, i)
|
||||
if keyLine == "" {
|
||||
// there is no keyLine for this sequence node
|
||||
// all of those lines are comments
|
||||
continue
|
||||
}
|
||||
|
||||
// keyLine is the line before the first sequence element
|
||||
keyLine := lines[i-1]
|
||||
|
||||
numSpacesBeforeKeyElem := len(keyLine) - len(strings.TrimLeft(keyLine, " "))
|
||||
trimmedKeyLine := strings.Trim(keyLine, " ")
|
||||
if strings.Count(trimmedKeyLine, ":") != 1 || !strings.HasSuffix(trimmedKeyLine, ":") {
|
||||
@@ -47,3 +47,22 @@ func DeriveSeqIndentStyle(originalYAML string) string {
|
||||
|
||||
return string(CompactSequenceStyle)
|
||||
}
|
||||
|
||||
// keyLineBeforeSeqElem iterates through the lines before the first seqElement
|
||||
// and tries to find the non-comment key line for the sequence node
|
||||
func keyLineBeforeSeqElem(lines []string, seqElemIndex int) string {
|
||||
// start with the previous line of sequence element
|
||||
i := seqElemIndex - 1
|
||||
for ; i >= 0; i-- {
|
||||
line := lines[i]
|
||||
trimmedLine := strings.Trim(line, " ")
|
||||
if strings.HasPrefix(trimmedLine, "#") { // commented line
|
||||
continue
|
||||
}
|
||||
// we have a non-commented line which can have a trailing comment
|
||||
parts := strings.SplitN(line, "#", 2)
|
||||
return parts[0] // throw away the trailing comment part
|
||||
}
|
||||
return ""
|
||||
|
||||
}
|
||||
|
||||
@@ -118,6 +118,21 @@ spec: +
|
||||
`,
|
||||
expectedOutput: `compact`,
|
||||
},
|
||||
{
|
||||
name: "handle comments",
|
||||
input: `apiVersion: v1
|
||||
kind: Service
|
||||
spec:
|
||||
ports: # comment 1
|
||||
# comment 2
|
||||
- name: etcd-server-ssl
|
||||
port: 2380
|
||||
# comment 3
|
||||
- name: etcd-client-ssl
|
||||
port: 2379
|
||||
`,
|
||||
expectedOutput: `wide`,
|
||||
},
|
||||
{
|
||||
name: "nested wide vs compact",
|
||||
input: `apiVersion: apps/v1
|
||||
@@ -140,6 +155,15 @@ abc:
|
||||
input: ` - foo`,
|
||||
expectedOutput: `compact`,
|
||||
},
|
||||
{
|
||||
name: "invalid resource but valid yaml sequence with comments",
|
||||
input: `
|
||||
# comment 1
|
||||
# comment 2
|
||||
- foo
|
||||
`,
|
||||
expectedOutput: `compact`,
|
||||
},
|
||||
{
|
||||
name: "- within sequence element",
|
||||
input: `apiVersion: apps/v1
|
||||
|
||||
Reference in New Issue
Block a user