diff --git a/pkg/config/envvar/envvar.go b/pkg/config/envvar/envvar.go index 850e1b2f1..c153d5196 100644 --- a/pkg/config/envvar/envvar.go +++ b/pkg/config/envvar/envvar.go @@ -11,6 +11,11 @@ import ( ) func ExpandInContent(content []byte) ([]byte, error) { + content, err := removeComments(content) + if err != nil { + return nil, fmt.Errorf("cannot remove configuration commented lines, error: %w", err) + } + r := regexp.MustCompile(`({{ *\w+.*?}})`) matches := r.FindAllIndex(content, -1) @@ -43,3 +48,30 @@ func ExpandInContent(content []byte) ([]byte, error) { return newContent, nil } + +func removeComments(content []byte) ([]byte, error) { + r := regexp.MustCompile(`(^[ \t#].*\n)|([ \t]*#.*)`) + matches := r.FindAllIndex(content, -1) + if len(matches) == 0 { + return content, nil + } + + var newContent []byte + var lastReplacement int + for _, idx := range matches { + lineStart := idx[0] + lineEnd := idx[1] + if len(content) < lineStart || len(content) < lineEnd { + return content, fmt.Errorf("cannot remove commented lines from config") + } + newContent = append(newContent, content[lastReplacement:lineStart]...) + lastReplacement = lineEnd + + } + + if lastReplacement != len(content) { + newContent = append(newContent, content[lastReplacement:]...) + } + + return newContent, nil +} diff --git a/pkg/config/envvar/envvar_test.go b/pkg/config/envvar/envvar_test.go index ad9432186..bbffb7dfa 100644 --- a/pkg/config/envvar/envvar_test.go +++ b/pkg/config/envvar/envvar_test.go @@ -30,6 +30,11 @@ func TestExpandInContent(t *testing.T) { {"2 placeholder with 2 env-var", map[string]string{"BAR1": "VAL1", "BAR2": "VAL2"}, "foo: {{BAR1}}\nbaz: {{BAR2}}", "foo: VAL1\nbaz: VAL2", false}, {"1 placeholder with 1 env-var special chars", map[string]string{"BAR": "$.*^"}, "foo: {{BAR}}\nbaz", "foo: $.*^\nbaz", false}, {"1 placeholder with 1 env-var numeric", map[string]string{"BAR": "1"}, "foo: {{BAR}}", "foo: 1", false}, + // comments removal + {"1 placeholder within comment lines are stripped", emptyEnv, "#foo: {{BAR}}\nbaz", "baz", false}, + {"comment lines starting with spaces are stripped", emptyEnv, " #foo: {{BAR}}\nbaz", "baz", false}, + {"comment lines starting with tab are stripped", emptyEnv, "\t #foo: {{BAR}}\nbaz", "baz", false}, + {"comment part of the line is dropped while previous content is kept", emptyEnv, "foo: bar # {{BAR}}\nbaz", "foo: bar\nbaz", false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {