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

Make string variable interpolation deterministic, and single-pass. #3024

Merged
merged 1 commit into from
Jul 31, 2020
Merged
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
8 changes: 6 additions & 2 deletions pkg/substitution/substitution.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,14 @@ func matchGroups(matches []string, pattern *regexp.Regexp) map[string]string {
}

func ApplyReplacements(in string, replacements map[string]string) string {
replacementsList := []string{}
for k, v := range replacements {
in = strings.Replace(in, fmt.Sprintf("$(%s)", k), v, -1)
replacementsList = append(replacementsList, fmt.Sprintf("$(%s)", k), v)
}
return in
// strings.Replacer does all replacements in one pass, preventing multiple replacements
// See #2093 for an explanation on why we need to do this.
replacer := strings.NewReplacer(replacementsList...)
return replacer.Replace(in)
}

// Take an input string, and output an array of strings related to possible arrayReplacements. If there aren't any
Expand Down
18 changes: 18 additions & 0 deletions pkg/substitution/substitution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,24 @@ func TestApplyReplacements(t *testing.T) {
}
}

func TestNestedReplacements(t *testing.T) {
replacements := map[string]string{
// Foo should turn into barbar, which could then expand into bazbaz depending on how this is expanded
"foo": "$(bar)$(bar)",
"bar": "baz",
}
input := "$(foo) is cool"
expected := "$(bar)$(bar) is cool"

// Run this test a lot of times to ensure the behavior is deterministic
for i := 0; i <= 1000; i++ {
got := substitution.ApplyReplacements(input, replacements)
if d := cmp.Diff(expected, got); d != "" {
t.Errorf("ApplyReplacements() output did not match expected value %s", diff.PrintWantGot(d))
}
}
}

func TestApplyArrayReplacements(t *testing.T) {
type args struct {
input string
Expand Down