-
Notifications
You must be signed in to change notification settings - Fork 1
feat: add shared regex match/replace engine #100
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
Open
leno23
wants to merge
1
commit into
dolph:main
Choose a base branch
from
leno23:feat/regex-engine-issue-37-v2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "regexp" | ||
| ) | ||
|
|
||
| // Pattern is the shared match/replace engine for file contents and renames. | ||
| // Literal mode escapes the pattern with regexp.QuoteMeta so existing | ||
| // find/replace semantics are preserved without exposing a regex flag yet. | ||
| type Pattern struct { | ||
| re *regexp.Regexp | ||
| replace string | ||
| literal bool | ||
| } | ||
|
|
||
| // Compile builds a Pattern. When literal is true, pattern is treated as a | ||
| // plain string; otherwise it is interpreted as RE2 syntax with $N capture | ||
| // references supported in replacement. | ||
| func Compile(pattern, replacement string, literal bool) (*Pattern, error) { | ||
| expr := pattern | ||
| if literal { | ||
| expr = regexp.QuoteMeta(pattern) | ||
| } | ||
| re, err := regexp.Compile(expr) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("compile pattern: %w", err) | ||
| } | ||
| return &Pattern{ | ||
| re: re, | ||
| replace: replacement, | ||
| literal: literal, | ||
| }, nil | ||
| } | ||
|
|
||
| func (p *Pattern) Match(s string) bool { | ||
| return p.re.MatchString(s) | ||
| } | ||
|
|
||
| func (p *Pattern) Replace(s string) string { | ||
| return p.re.ReplaceAllString(s, p.replace) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestCompile_LiteralModeMatchesPlainString(t *testing.T) { | ||
| p, err := Compile("foo.bar", "X", true) | ||
| if err != nil { | ||
| t.Fatalf("Compile() err = %v", err) | ||
| } | ||
| if !p.Match("foo.bar") { | ||
| t.Error("Match() = false; want true for literal dot") | ||
| } | ||
| if p.Match("fooXbar") { | ||
| t.Error("Match() = true; want false") | ||
| } | ||
| if got := p.Replace("foo.bar baz"); got != "X baz" { | ||
| t.Errorf("Replace() = %q; want %q", got, "X baz") | ||
| } | ||
| } | ||
|
|
||
| func TestCompile_LiteralModeEquivalentToReplaceAll(t *testing.T) { | ||
| cases := []struct { | ||
| find, replace, input string | ||
| }{ | ||
| {"alpha", "beta", "alpha alpha"}, | ||
| {"(parens)", "[brackets]", "file (parens).txt"}, | ||
| {"$dollar", "cent", "cost $dollar"}, | ||
| {"a.b", "ab", "a.b.c"}, | ||
| } | ||
| for _, tc := range cases { | ||
| p, err := Compile(tc.find, tc.replace, true) | ||
| if err != nil { | ||
| t.Fatalf("Compile(%q): %v", tc.find, err) | ||
| } | ||
| want := strings.ReplaceAll(tc.input, tc.find, tc.replace) | ||
| if got := p.Replace(tc.input); got != want { | ||
| t.Errorf("Replace(%q, %q) on %q = %q; want %q", tc.find, tc.replace, tc.input, got, want) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestCompile_CaptureGroups(t *testing.T) { | ||
| p, err := Compile(`(\w+)@(\w+)\.(\w+)`, "$2.$1@$3", false) | ||
| if err != nil { | ||
| t.Fatalf("Compile() err = %v", err) | ||
| } | ||
| got := p.Replace("alice@example.com") | ||
| if got != "example.alice@com" { | ||
| t.Errorf("Replace() = %q; want example.alice@com", got) | ||
| } | ||
| } | ||
|
|
||
| func TestCompile_NamedCaptureGroup(t *testing.T) { | ||
| p, err := Compile(`(?P<first>\w+) (?P<last>\w+)`, "${last}, ${first}", false) | ||
| if err != nil { | ||
| t.Fatalf("Compile() err = %v", err) | ||
| } | ||
| got := p.Replace("Ada Lovelace") | ||
| if got != "Lovelace, Ada" { | ||
| t.Errorf("Replace() = %q; want Lovelace, Ada", got) | ||
| } | ||
| } | ||
|
|
||
| func TestCompile_ReplacementEscapes(t *testing.T) { | ||
| p, err := Compile(`(\d+)`, "$$1 cents", false) | ||
| if err != nil { | ||
| t.Fatalf("Compile() err = %v", err) | ||
| } | ||
| if got := p.Replace("42"); got != "$1 cents" { | ||
| t.Errorf("Replace() = %q; want %q", got, "$1 cents") | ||
| } | ||
| } | ||
|
|
||
| func TestCompile_InvalidPatternReturnsError(t *testing.T) { | ||
| _, err := Compile("[unclosed", "x", false) | ||
| if err == nil { | ||
| t.Fatal("Compile() err = nil; want error") | ||
| } | ||
| } | ||
|
|
||
| func BenchmarkPatternLiteralReplace(b *testing.B) { | ||
| input := strings.Repeat("alpha beta gamma ", 1000) | ||
| p, err := Compile("alpha", "beta", true) | ||
| if err != nil { | ||
| b.Fatal(err) | ||
| } | ||
| b.ResetTimer() | ||
| for i := 0; i < b.N; i++ { | ||
| _ = p.Replace(input) | ||
| } | ||
| } | ||
|
|
||
| func BenchmarkStringsReplaceAllLiteral(b *testing.B) { | ||
| input := strings.Repeat("alpha beta gamma ", 1000) | ||
| b.ResetTimer() | ||
| for i := 0; i < b.N; i++ { | ||
| _ = strings.ReplaceAll(input, "alpha", "beta") | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the CLI still compiles patterns in literal mode, using
regexp.ReplaceAllStringchanges the documentedstrings.ReplaceAllbehavior for replacement strings containing$: values like$1,${name}, or$$are expanded/collapsed as regexp replacement syntax instead of being written literally. For example, replacingfoowith$HOMEin file contents or names will not produce$HOME, so existing invocations that use dollar signs in the replacement corrupt the output despite no regex flag being exposed yet.Useful? React with 👍 / 👎.