Debian Codegraph @

kyaml/yaml/util.go

raw symbols SCIP
1 // Copyright 2021 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package yaml
5
6 import (
7 "strings"
8 )
9
10 // DeriveSeqIndentStyle derives the sequence indentation annotation value for the resource,
11 // originalYAML is the input yaml string,
12 // the style is decided by deriving the existing sequence indentation of first sequence node
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 // prefix of "- " must be sequence of spaces
21 if strings.Trim(elems[0], " ") != "" {
22 continue
23 }
24 numSpacesBeforeSeqElem := len(elems[0])
25
26 // keyLine is the line before the first sequence element
27 keyLine := keyLineBeforeSeqElem(lines, i)
28 if keyLine == "" {
29 // there is no keyLine for this sequence node
30 // all of those lines are comments
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 // if the key line doesn't contain only one : that too at the end,
37 // this is not a sequence node, it is a wrapped sequence node string
38 // ignore it
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 // keyLineBeforeSeqElem iterates through the lines before the first seqElement
55 // and tries to find the non-comment key line for the sequence node
56 func keyLineBeforeSeqElem(lines []string, seqElemIndex int) string {
57 // start with the previous line of sequence element
58 i := seqElemIndex - 1
59 for ; i >= 0; i-- {
60 line := lines[i]
61 trimmedLine := strings.Trim(line, " ")
62 if strings.HasPrefix(trimmedLine, "#") { // commented line
63 continue
64 }
65 // we have a non-commented line which can have a trailing comment
66 parts := strings.SplitN(line, "#", 2)
67 return parts[0] // throw away the trailing comment part
68 }
69 return ""
70 }