diff --git a/pkg/policy/checker.go b/pkg/policy/checker.go index 6b0c1e00..8935d868 100644 --- a/pkg/policy/checker.go +++ b/pkg/policy/checker.go @@ -82,12 +82,15 @@ func TopKeys(helmfileContent []byte, hasSeparator bool) []string { clines := bytes.Split(helmfileContent, []byte("\n")) for _, line := range clines { - if topConfigKeysRegex.Match(line) { - lineStr := strings.Split(string(line), ":")[0] - topKeys = append(topKeys, lineStr) + lineStr := strings.TrimSpace(string(line)) + if lineStr == "" { + continue // Skip empty lines } - if hasSeparator && separatorRegex.Match(line) { - topKeys = append(topKeys, strings.TrimSpace(string(line))) + if hasSeparator && separatorRegex.MatchString(lineStr) { + topKeys = append(topKeys, lineStr) + } else if topConfigKeysRegex.MatchString(lineStr) { + topKey := strings.SplitN(lineStr, ":", 2)[0] + topKeys = append(topKeys, topKey) } } return topKeys diff --git a/pkg/policy/checker_test.go b/pkg/policy/checker_test.go index 5e81d9ce..b867b4ad 100644 --- a/pkg/policy/checker_test.go +++ b/pkg/policy/checker_test.go @@ -239,3 +239,30 @@ func TestTopKeys(t *testing.T) { }) } } + +func TestTopKeys_MalformedLines(t *testing.T) { + tests := []struct { + name string + helmfileContent []byte + hasSeparator bool + want []string + }{ + { + name: "malformed lines with special characters", + helmfileContent: []byte("bas@es:\nenvironm*ents:\nrele#ases:\n"), + want: nil, // This test expects no valid top keys + }, + { + name: "malformed lines with incomplete key", + helmfileContent: []byte("bases\nenvironments:\nreleases:\n"), + want: []string{"environments", "releases"}, // This test expects only valid top keys + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := TopKeys(tt.helmfileContent, tt.hasSeparator) + require.Equal(t, tt.want, got, "expected %v, got=%v", tt.want, got) + }) + } +}