Skip to content

Commit

Permalink
Drop comments from config files (#272)
Browse files Browse the repository at this point in the history
* feat: drop commented lines from config files

* feat: drop comments, not lines, from config files
  • Loading branch information
varas authored Dec 16, 2020
1 parent de6490d commit 7f863c1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
32 changes: 32 additions & 0 deletions pkg/config/envvar/envvar.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
}
5 changes: 5 additions & 0 deletions pkg/config/envvar/envvar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 7f863c1

Please sign in to comment.