Skip to content

Commit

Permalink
feat: add regex.replace(s, p, v): add more tests to cover exceptions …
Browse files Browse the repository at this point in the history
…and migrate to RegisterBuiltinFunc

Signed-off-by: boranx <boran.seref@gmail.com>
  • Loading branch information
boranx authored and anderseknert committed Sep 27, 2022
1 parent e98084a commit 8ce699c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 12 deletions.
29 changes: 27 additions & 2 deletions test/cases/testdata/regexreplace/test-regexreplace-0001.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,32 @@ cases:
s := "-wy-wxxy-"
x := regex.replace(s, "w(x*)y", "0")
}
note: test regex.replace
note: 'regex.replace: test pattern match and replace'
query: data.test.p = x
want_result:
- x: -0-0-
- x: -0-0-
- data: {}
modules:
- |
package test
p = x {
s := "foo"
x := regex.replace(s, "(foo)", "$1$1")
}
note: 'regex.replace: work with groups'
query: data.test.p = x
want_result:
- x: foofoo
- data: {}
modules:
- |
package test
p = x {
s := "foo"
x := regex.replace(s, "[", "$1")
}
note: 'regex.replace: bad regex pattern: Syntax error'
query: data.test.p = x
want_result: []
20 changes: 10 additions & 10 deletions topdown/regex.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,30 +205,30 @@ func builtinRegexFindAllStringSubmatch(a, b, c ast.Value) (ast.Value, error) {
return ast.NewArray(outer...), nil
}

func builtinRegexReplace(a, b, c ast.Value) (ast.Value, error) {
base, err := builtins.StringOperand(a, 1)
func builtinRegexReplace(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
base, err := builtins.StringOperand(operands[0].Value, 1)
if err != nil {
return nil, err
return err
}

pattern, err := builtins.StringOperand(b, 2)
pattern, err := builtins.StringOperand(operands[1].Value, 2)
if err != nil {
return nil, err
return err
}

value, err := builtins.StringOperand(c, 3)
value, err := builtins.StringOperand(operands[2].Value, 3)
if err != nil {
return nil, err
return err
}

re, err := getRegexp(string(pattern))
if err != nil {
return nil, err
return err
}

res := re.ReplaceAllString(string(base), string(value))

return ast.String(res), nil
return iter(ast.StringTerm(res))
}

func init() {
Expand All @@ -241,5 +241,5 @@ func init() {
RegisterFunctionalBuiltin4(ast.RegexTemplateMatch.Name, builtinRegexMatchTemplate)
RegisterFunctionalBuiltin3(ast.RegexFind.Name, builtinRegexFind)
RegisterFunctionalBuiltin3(ast.RegexFindAllStringSubmatch.Name, builtinRegexFindAllStringSubmatch)
RegisterFunctionalBuiltin3(ast.RegexReplace.Name, builtinRegexReplace)
RegisterBuiltinFunc(ast.RegexReplace.Name, builtinRegexReplace)
}

0 comments on commit 8ce699c

Please sign in to comment.