added replace-all patch type
This commit is contained in:
parent
bb7da3e154
commit
3d08b492ac
5 changed files with 134 additions and 25 deletions
80
replace-all.go
Normal file
80
replace-all.go
Normal file
|
@ -0,0 +1,80 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// applyReplaceAllPatch performs global string replacements in all files
|
||||
func applyReplaceAllPatch(rootPath string, modifications []string) error {
|
||||
replacements := [][2]string{}
|
||||
for _, mod := range modifications {
|
||||
parts := strings.SplitN(mod, "=>", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
from := strings.TrimSpace(parts[0])
|
||||
to := strings.TrimSpace(parts[1])
|
||||
replacements = append(replacements, [2]string{from, to})
|
||||
}
|
||||
|
||||
// Get absolute path of the patcher's own directory
|
||||
selfPath, err := os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot resolve own path: %v", err)
|
||||
}
|
||||
patcherDir := filepath.Dir(selfPath)
|
||||
|
||||
return filepath.WalkDir(rootPath, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
// Skip patcher's own directory and subdirectories
|
||||
if strings.HasPrefix(path, patcherDir) {
|
||||
return fs.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Skip patcher's own files
|
||||
if strings.HasPrefix(path, patcherDir) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Only patch known text/code files
|
||||
if strings.HasSuffix(path, ".cpp") || strings.HasSuffix(path, ".h") ||
|
||||
strings.HasSuffix(path, ".c") || strings.HasSuffix(path, ".go") ||
|
||||
strings.HasSuffix(path, ".js") || strings.HasSuffix(path, ".ts") ||
|
||||
strings.HasSuffix(path, ".html") || strings.HasSuffix(path, ".in") ||
|
||||
strings.HasSuffix(path, ".mjs") || strings.HasSuffix(path, ".txt") {
|
||||
return replaceInFile(path, replacements)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// replaceInFile performs replacements in one file
|
||||
func replaceInFile(filePath string, replacements [][2]string) error {
|
||||
content, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
text := string(content)
|
||||
original := text
|
||||
|
||||
for _, repl := range replacements {
|
||||
text = strings.ReplaceAll(text, repl[0], repl[1])
|
||||
}
|
||||
|
||||
if text != original {
|
||||
err = os.WriteFile(filePath, []byte(text), 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write modified file: %v", err)
|
||||
}
|
||||
fmt.Printf("Replaced content in: %s\n", filePath)
|
||||
}
|
||||
return nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue