Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve CRD template field insertion line targeting #4268

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -91,12 +91,7 @@ func realMain(helmPath string) error {
` release: {{ .Release.Name }}`,
` component: crd`,
}
var split int
if dir == "bases" {
split = 6
} else {
split = 9
}
split := findSplit(splitOnNewlines, []string{"metadata", "name"})
withLabels := append(splitOnNewlines[0:split], append(labelLines, splitOnNewlines[split:]...)...)
contents = strings.Join(withLabels, "\n")

Expand Down Expand Up @@ -128,6 +123,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
Loading