From bd7857f8b4907538c3b3b7d53a742d52507bb3ab Mon Sep 17 00:00:00 2001 From: Michael Guarino Date: Wed, 2 Dec 2026 20:10:46 +0000 Subject: [PATCH 1/2] Validate pr template regexes up front, and stop recursive matches panicking An automation's regexes were compiled lazily while applying it: regex replacements first, file updates per file during the walk. An invalid one failed halfway, after earlier files had changed, with Go's bare "error parsing regexp" naming neither the field nor the replacement. With the recursive match strategy, an invalid regex after the first panicked out of ReplaceAllFunc. * Apply compiles every regex the updates use (regexReplacements, files and regexes, rendered the way applying them renders them) after Lua and before anything is written, and reports e.g. updates.regexReplacements[1].regex "(image: (.*)" isn't a valid regular expression: missing closing ) * recursiveReplace returns a nested error instead of panicking Co-Authored-By: Claude Opus 5.5 --- pkg/pr/apply.go | 5 +++ pkg/pr/updates.go | 26 +++++++-------- pkg/pr/validate.go | 52 +++++++++++++++++++++++++++++ pkg/pr/validate_test.go | 74 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 143 insertions(+), 14 deletions(-) create mode 100644 pkg/pr/validate.go create mode 100644 pkg/pr/validate_test.go diff --git a/pkg/pr/apply.go b/pkg/pr/apply.go index 800648cad..984700439 100644 --- a/pkg/pr/apply.go +++ b/pkg/pr/apply.go @@ -9,6 +9,11 @@ func Apply(template *PrTemplate) error { return err } + // after Lua, which can change the spec, and before anything is written + if err := validateRegexes(template.Spec.Updates, template.Context); err != nil { + return err + } + if err := applyVendoring(template, template.Context); err != nil { return err } diff --git a/pkg/pr/updates.go b/pkg/pr/updates.go index 0682f0882..0885f026a 100644 --- a/pkg/pr/updates.go +++ b/pkg/pr/updates.go @@ -30,13 +30,7 @@ func applyUpdates(updates *UpdateSpec, ctx map[string]interface{}) error { return err } - files := lo.Map(updates.Files, func(name string, ind int) string { - res, err := templateReplacement([]byte(name), ctx) - if err != nil { - return name - } - return string(res) - }) + files := lo.Map(updates.Files, func(name string, _ int) string { return renderRegex(name, ctx) }) return filepath.Walk(".", func(path string, info fs.FileInfo, err error) error { if err != nil { @@ -72,12 +66,7 @@ func processRegexReplacements(replacements []RegexReplacement, ctx map[string]in } replaceFunc := func(data []byte) ([]byte, error) { - rx, err := templateReplacement([]byte(replacement.Regex), ctx) - if err != nil { - rx = []byte(replacement.Regex) - } - - r, err := regexp.Compile(string(rx)) + r, err := regexp.Compile(renderRegex(replacement.Regex, ctx)) if err != nil { return data, err } @@ -214,13 +203,22 @@ func recursiveReplace(data []byte, regexes []string, replacement []byte) ([]byte return data, err } + // a nested error used to panic out of ReplaceAllFunc; it's returned like any other now + var nested error res := r.ReplaceAllFunc(data, func(d []byte) []byte { + if nested != nil { + return d + } res, err := recursiveReplace(d, regexes[1:], replacement) if err != nil { - panic(err) + nested = err + return d } return res }) + if nested != nil { + return data, nested + } return res, nil } diff --git a/pkg/pr/validate.go b/pkg/pr/validate.go new file mode 100644 index 000000000..684d389f5 --- /dev/null +++ b/pkg/pr/validate.go @@ -0,0 +1,52 @@ +package pr + +import ( + "errors" + "fmt" + "regexp" + "regexp/syntax" +) + +// validateRegexes compiles every regular expression the updates will use, rendered the way applying them renders +// them, so an invalid one fails the template before any file is written, with an error naming the field and the +// pattern. Compiling them lazily, per file, let an invalid one fail halfway through, after earlier files had changed. +func validateRegexes(updates *UpdateSpec, ctx map[string]interface{}) error { + if updates == nil { + return nil + } + + var errs []error + check := func(field, rx string) { + if _, err := regexp.Compile(rx); err != nil { + errs = append(errs, regexError(field, rx, err)) + } + } + for i, replacement := range updates.RegexReplacements { + check(fmt.Sprintf("updates.regexReplacements[%d].regex", i), renderRegex(replacement.Regex, ctx)) + } + for i, file := range updates.Files { + check(fmt.Sprintf("updates.files[%d]", i), renderRegex(file, ctx)) + } + for i, rx := range updates.Regexes { + check(fmt.Sprintf("updates.regexes[%d]", i), rx) + } + return errors.Join(errs...) +} + +// renderRegex templates a regular expression the way applying it does: one whose template doesn't render is used as +// written. +func renderRegex(rx string, ctx map[string]interface{}) string { + res, err := templateReplacement([]byte(rx), ctx) + if err != nil { + return rx + } + return string(res) +} + +func regexError(field, rx string, err error) error { + var se *syntax.Error + if errors.As(err, &se) { + return fmt.Errorf("%s %q isn't a valid regular expression: %s", field, rx, se.Code) + } + return fmt.Errorf("%s %q isn't a valid regular expression: %w", field, rx, err) +} diff --git a/pkg/pr/validate_test.go b/pkg/pr/validate_test.go new file mode 100644 index 000000000..30b9c9911 --- /dev/null +++ b/pkg/pr/validate_test.go @@ -0,0 +1,74 @@ +package pr_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/pluralsh/plural-cli/pkg/pr" +) + +func TestApplyRejectsInvalidRegexes(t *testing.T) { + cases := []struct { + name string + updates *pr.UpdateSpec + ctx map[string]interface{} + err string + }{ + { + // the pattern a user's pull request automation failed on, as "unknown error" in console + name: "an unbalanced regex replacement", + updates: &pr.UpdateSpec{RegexReplacements: []pr.RegexReplacement{ + {Regex: `tag: (.*)`, Replacement: "tag: v2", File: "values.yaml"}, + {Regex: `(image: (.*)`, Replacement: "x", File: "values.yaml"}, + }}, + err: `updates.regexReplacements[1].regex "(image: (.*)" isn't a valid regular expression: missing closing )`, + }, + { + name: "a templated regex replacement is checked as rendered", + updates: &pr.UpdateSpec{RegexReplacements: []pr.RegexReplacement{{Regex: `{{ context.key }}: (.*`, Replacement: "x", File: "values.yaml"}}}, + ctx: map[string]interface{}{"key": "image"}, + err: `updates.regexReplacements[0].regex "image: (.*" isn't a valid regular expression: missing closing )`, + }, + { + name: "file patterns", + updates: &pr.UpdateSpec{Files: []string{`values[.yaml`}, MatchStrategy: "any", Regexes: []string{"a"}}, + err: `updates.files[0] "values[.yaml" isn't a valid regular expression: missing closing ]`, + }, + { + name: "PCRE-only syntax RE2 doesn't support", + updates: &pr.UpdateSpec{Files: []string{`.*`}, MatchStrategy: "any", Regexes: []string{`image: (?=v)(.*)`}}, + err: `updates.regexes[0] "image: (?=v)(.*)" isn't a valid regular expression: invalid or unsupported Perl syntax`, + }, + { + // it used to panic out of ReplaceAllFunc while recursing; it's caught up front now + name: "an invalid regex after the first in a recursive match", + updates: &pr.UpdateSpec{Files: []string{`.*`}, MatchStrategy: "recursive", Regexes: []string{`image: (.*)`, `(v[0-9]`}}, + err: `updates.regexes[1] "(v[0-9]" isn't a valid regular expression: missing closing )`, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + wd, err := os.Getwd() + require.NoError(t, err) + require.NoError(t, os.Chdir(dir)) + t.Cleanup(func() { _ = os.Chdir(wd) }) + const values = "image: nginx\ntag: v1\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "values.yaml"), []byte(values), 0o644)) + + err = pr.Apply(&pr.PrTemplate{Context: tc.ctx, Spec: pr.PrTemplateSpec{Updates: tc.updates}}) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.err) + + // nothing is written when any regex is invalid, even one that would have been applied first + data, err := os.ReadFile(filepath.Join(dir, "values.yaml")) + require.NoError(t, err) + assert.Equal(t, values, string(data)) + }) + } +} From 6649991d2e4d66acb1acf7cd81bb1a8a349707f5 Mon Sep 17 00:00:00 2001 From: Michael Guarino Date: Wed, 2 Dec 2026 20:41:55 +0000 Subject: [PATCH 2/2] Test recursiveReplace's nested error directly Apply rejects invalid regexes up front now, so TestApplyRejectsInvalidRegexes never reaches recursiveReplace. Call it directly with a matching first pattern and an invalid second one: it returns the error without panicking and leaves the input unchanged (the test fails against the old panic). Co-Authored-By: Claude Opus 5.5 --- pkg/pr/updates_internal_test.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 pkg/pr/updates_internal_test.go diff --git a/pkg/pr/updates_internal_test.go b/pkg/pr/updates_internal_test.go new file mode 100644 index 000000000..e2c2f1735 --- /dev/null +++ b/pkg/pr/updates_internal_test.go @@ -0,0 +1,33 @@ +package pr + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Apply rejects invalid regexes before it gets here (validateRegexes), so this exercises recursiveReplace directly: +// a nested regex that doesn't compile used to panic out of ReplaceAllFunc. +func TestRecursiveReplaceReturnsNestedErrors(t *testing.T) { + data := []byte("image: nginx:v1\n") + + var ( + res []byte + err error + ) + require.NotPanics(t, func() { + // the first regex matches, so the invalid second one is only compiled while recursing + res, err = recursiveReplace(data, []string{`image: (.*)`, `(v[0-9]`}, []byte("v2")) + }) + + require.Error(t, err) + assert.Contains(t, err.Error(), "missing closing )") + assert.Equal(t, data, res, "the input comes back unchanged") +} + +func TestRecursiveReplaceReplacesNestedMatches(t *testing.T) { + res, err := recursiveReplace([]byte("image: nginx:v1\n"), []string{`image: .*`, `v[0-9]+`}, []byte("v2")) + require.NoError(t, err) + assert.Equal(t, "image: nginx:v2\n", string(res)) +}