Skip to content
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
5 changes: 5 additions & 0 deletions pkg/pr/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
26 changes: 12 additions & 14 deletions pkg/pr/updates.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
33 changes: 33 additions & 0 deletions pkg/pr/updates_internal_test.go
Original file line number Diff line number Diff line change
@@ -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))
}
52 changes: 52 additions & 0 deletions pkg/pr/validate.go
Original file line number Diff line number Diff line change
@@ -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)
}
74 changes: 74 additions & 0 deletions pkg/pr/validate_test.go
Original file line number Diff line number Diff line change
@@ -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 )`,
Comment thread
michaeljguarino marked this conversation as resolved.
Resolved
},
}

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))
})
}
}
Loading