added tool renamer

This commit is contained in:
Pasha 2024-11-07 11:45:29 +03:00
parent 662272e5f0
commit 4a2f581a40
2 changed files with 88 additions and 0 deletions

1
renamer/go.mod Normal file

@ -0,0 +1 @@
module renamer

87
renamer/main.go Normal file

@ -0,0 +1,87 @@
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
)
// example go run main.go "penahub.gitlab.yandexcloud.net/external/trashlog" "gitea.pena/PenaSide/trashlog" C:\Users\Pavel\GolandProjects\sheet\core C:\Users\Pavel\GolandProjects\sheet\answerer
func main() {
if len(os.Args) < 4 {
fmt.Println("Использовать: go run main.go <старый импорт, который убираем> <новый импорт, на который меняем> <путь до проекта1 путь до проекта2 ...")
return
}
oldImport := os.Args[1]
newImport := os.Args[2]
projectPaths := os.Args[3:]
for _, projectPath := range projectPaths {
err := filepath.Walk(projectPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(path) == ".go" {
err = replaceImportInFile(path, oldImport, newImport)
if err != nil {
fmt.Printf("Ошибка форматирования файла %s: %v\n", path, err)
}
}
return nil
})
if err != nil {
fmt.Printf("Ошибка прохода по файлу %s: %v\n", projectPath, err)
}
}
}
func replaceImportInFile(filePath, oldImport, newImport string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
var output []string
scanner := bufio.NewScanner(file)
changed := false
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, oldImport) {
line = strings.ReplaceAll(line, oldImport, newImport)
changed = true
}
output = append(output, line)
}
if err := scanner.Err(); err != nil {
return err
}
if !changed {
return nil
}
file.Close()
file, err = os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for _, line := range output {
_, err := writer.WriteString(line + "\n")
if err != nil {
return err
}
}
return writer.Flush()
}