Skip to content

Commit

Permalink
improve CRD template field insertion line targeting
Browse files Browse the repository at this point in the history
  • Loading branch information
zalimeni committed Aug 28, 2024
1 parent 3e837ee commit daca3bc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion hack/copy-crds-to-chart/go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/hashicorp/consul-k8s/hack/copy-crds-to-chart

go 1.20
go 1.21
34 changes: 28 additions & 6 deletions hack/copy-crds-to-chart/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,7 @@ func realMain(helmPath string) error {
` release: {{ .Release.Name }}`,
` component: crd`,
}
var split int
if dir == "bases" {
split = 8
} else {
split = 9
}
split := findSplit(splitOnNewlines, []string{"metadata", "name"})
withLabels := append(splitOnNewlines[0:split], append(labelLines, splitOnNewlines[split:]...)...)
contents = strings.Join(withLabels, "\n")

Expand All @@ -110,6 +105,33 @@ func realMain(helmPath string) error {
return nil
}

// findSplit finds the line number immediately following the given yamlPath elements.
// It assumes the first match of each element is the correct one (i.e. it will not attempt
// further path traversals after a partial match). This is a quick and dirty substitute for
// YAML parsing so we can insert content after known fields.
func findSplit(lines []string, yamlPath []string) int {
yamlPathIdx := 0
getIndent := func(line string) int {
return len(line) - len(strings.TrimLeft(line, " "))
}
minIndent := getIndent(lines[0])
for i, line := range lines {
if strings.Contains(line, yamlPath[yamlPathIdx]) &&
strings.HasPrefix(line, strings.Repeat(" ", minIndent)) {
if yamlPathIdx < len(yamlPath)-1 {
yamlPathIdx++
// Ensure we don't leave the current search path by increasing the
// minimum expected indent to match the next line.
minIndent = max(minIndent, getIndent(lines[i+1]))
} else {
// We found it! Return next line number.
return i + 1
}
}
}
panic("could not find YAML field: " + strings.Join(yamlPath, "."))
}

func printf(format string, args ...interface{}) {
fmt.Println(fmt.Sprintf(format, args...))
}
Expand Down

0 comments on commit daca3bc

Please sign in to comment.