Skip to content

Commit

Permalink
Merge pull request #1 from bmorton/add-regexp-support
Browse files Browse the repository at this point in the history
Add regexp support via --regexp flag
  • Loading branch information
bmorton authored Nov 16, 2022
2 parents bf3c33a + cbd73bc commit 05d57a6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 5 additions & 0 deletions cmd/replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ var ReplaceCommand = &cli.Command{
Name: "dry-run",
Usage: "output changed files to stdout instead of committing",
},
&cli.BoolFlag{
Name: "regexp",
Usage: "enable regular expression mode for find string",
},
&cli.StringFlag{
Name: "title",
Usage: "title for pull request",
Expand Down Expand Up @@ -88,6 +92,7 @@ func replaceAction(ctx *cli.Context) error {
rep.Find = ctx.String("find")
rep.Replace = ctx.String("replace")
rep.Limit = ctx.Int("limit")
rep.Regexp = ctx.Bool("regexp")

return rep.Run(ctx.Context)
}
15 changes: 14 additions & 1 deletion replacer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"github.com/google/go-github/v48/github"
"regexp"
"strings"
"time"
)
Expand All @@ -18,13 +19,15 @@ type Replacer struct {
BaseBranch string
TargetBranch string
Path string
Mode string
Find string
Replace string
Limit int
Title string
Description string
DryRun bool
SkipPullRequest bool
Regexp bool
gh *github.Client
}

Expand Down Expand Up @@ -173,7 +176,17 @@ func (r Replacer) generateContent(ctx context.Context) (string, error) {
return "", err
}

newContent := strings.Replace(content, r.Find, r.Replace, r.Limit)
if strings.TrimSpace(content) == "" {
return "", fmt.Errorf("file %s is empty", r.Path)
}

var newContent string
if r.Regexp {
sampleRegexp := regexp.MustCompile(r.Find)
newContent = sampleRegexp.ReplaceAllString(content, r.Replace)
} else {
newContent = strings.Replace(content, r.Find, r.Replace, r.Limit)
}

if newContent == content {
return "", ErrNoContentChange
Expand Down

0 comments on commit 05d57a6

Please sign in to comment.