Skip to content

Commit

Permalink
Refine template mode
Browse files Browse the repository at this point in the history
  • Loading branch information
ayoisaiah committed May 24, 2020
1 parent c70801e commit 6a7781d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
5 changes: 5 additions & 0 deletions cmd/goname/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ func main() {
Aliases: []string{"D"},
Usage: "Rename directories",
},
&cli.BoolFlag{
Name: "template-mode",
Aliases: []string{"T"},
Usage: "Opt into template mode",
},
&cli.BoolFlag{
Name: "force",
Aliases: []string{"F"},
Expand Down
18 changes: 12 additions & 6 deletions cmd/goname/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type Operation struct {
replaceString string
exec bool
ignoreConflicts bool
templateMode bool
includeDir bool
searchRegex *regexp.Regexp
}
Expand All @@ -41,6 +42,10 @@ type Operation struct {
// if in execute mode. Conflicts will be ignored if
// specified
func (op *Operation) Apply() error {
if len(op.matches) == 0 {
return fmt.Errorf("Failed to match any files")
}

if !op.ignoreConflicts {
err := op.ReportConflicts()
if err != nil {
Expand Down Expand Up @@ -155,14 +160,13 @@ func (op *Operation) SortMatches() {
func (op *Operation) Replace() error {
og := regexp.MustCompile("{og}")
ext := regexp.MustCompile("{ext}")
index := regexp.MustCompile("%[0-9]+d")
index := regexp.MustCompile("%([0-9]?)+d")
for i, v := range op.matches {
fileName, dir := filepath.Base(v.source), filepath.Dir(v.source)
var str string

// If the search pattern is an empty string
if op.searchRegex.Match([]byte("")) {
// use replacement string as template for new name
if op.templateMode {
// Use the replacement string as a template for new name
str = op.replaceString
} else {
str = op.searchRegex.ReplaceAllString(fileName, op.replaceString)
Expand All @@ -187,8 +191,9 @@ func (op *Operation) Replace() error {
}

// Only perform find and replace on `dir`
// if file is a directory to avoid conflicts
if op.includeDir && v.isDir {
// if file is a directory and templateMode is off
// to avoid conflicts
if op.includeDir && v.isDir && !op.templateMode {
dir = op.searchRegex.ReplaceAllString(dir, op.replaceString)
}

Expand Down Expand Up @@ -218,6 +223,7 @@ func NewOperation(c *cli.Context) (*Operation, error) {
op.exec = c.Bool("exec")
op.ignoreConflicts = c.Bool("force")
op.includeDir = c.Bool("include-dir")
op.templateMode = c.Bool("template-mode")

findPattern := c.String("find")

Expand Down

0 comments on commit 6a7781d

Please sign in to comment.