74 lines
1.8 KiB
Go
74 lines
1.8 KiB
Go
package cmd
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/jasonross/text-shark/internal/fileops"
|
|
"github.com/jasonross/text-shark/internal/runner"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var (
|
|
replaceDryRun bool
|
|
replaceType string
|
|
replaceGlob string
|
|
replaceRegex bool
|
|
)
|
|
|
|
var replaceCmd = &cobra.Command{
|
|
Use: "replace <from> <to> [path]",
|
|
Short: "Replace all occurrences of <from> with <to> in files",
|
|
Args: cobra.RangeArgs(2, 3),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
from, to := args[0], args[1]
|
|
path := "."
|
|
if len(args) == 3 {
|
|
path = args[2]
|
|
}
|
|
|
|
var rgExtra []string
|
|
if replaceType != "" {
|
|
rgExtra = append(rgExtra, "--type", replaceType)
|
|
}
|
|
if replaceGlob != "" {
|
|
rgExtra = append(rgExtra, "--glob", replaceGlob)
|
|
}
|
|
|
|
files, err := runner.RgListFiles(from, path, rgExtra...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(files) == 0 {
|
|
fmt.Println("No matches found.")
|
|
return nil
|
|
}
|
|
|
|
var results []fileops.ReplaceResult
|
|
for _, f := range files {
|
|
var res fileops.ReplaceResult
|
|
if replaceRegex {
|
|
res, err = fileops.ReplaceInFileRegex(f, from, to, replaceDryRun)
|
|
} else {
|
|
res, err = fileops.ReplaceInFile(f, from, to, replaceDryRun)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s: %w", f, err)
|
|
}
|
|
results = append(results, res)
|
|
}
|
|
|
|
if replaceDryRun {
|
|
fmt.Println("[dry-run] would modify:")
|
|
}
|
|
fileops.PrintReplaceResults(results)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
replaceCmd.Flags().BoolVar(&replaceDryRun, "dry-run", false, "Print what would change without writing")
|
|
replaceCmd.Flags().StringVarP(&replaceType, "type", "t", "", "File type filter (e.g. go, py)")
|
|
replaceCmd.Flags().StringVarP(&replaceGlob, "glob", "g", "", "Glob pattern for file paths")
|
|
replaceCmd.Flags().BoolVarP(&replaceRegex, "regex", "r", false, "Treat <from> as a regular expression")
|
|
}
|