99 lines
2.6 KiB
Go
99 lines
2.6 KiB
Go
package renamer
|
||
|
||
import (
|
||
"fmt"
|
||
"io/fs"
|
||
"os"
|
||
"path/filepath"
|
||
"sort"
|
||
"strings"
|
||
|
||
"nertz/cleaner/internal/keywords"
|
||
)
|
||
|
||
// Config хранит параметры запуска утилиты.
|
||
type Config struct {
|
||
RootDir string
|
||
Filter *keywords.Filter
|
||
DryRun bool
|
||
}
|
||
|
||
// Run выполняет рекурсивный обход, удаление мусорных файлов и переименование.
|
||
func Run(cfg Config) error {
|
||
var paths []string
|
||
|
||
err := filepath.WalkDir(cfg.RootDir, func(path string, d fs.DirEntry, err error) error {
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if path == cfg.RootDir {
|
||
return nil
|
||
}
|
||
// Пропускаем скрытые директории (например, .git)
|
||
if d.IsDir() && strings.HasPrefix(d.Name(), ".") {
|
||
return filepath.SkipDir
|
||
}
|
||
paths = append(paths, path)
|
||
return nil
|
||
})
|
||
if err != nil {
|
||
return fmt.Errorf("ошибка при сканировании директории: %w", err)
|
||
}
|
||
|
||
// Сортируем от самых глубоких путей к верхним (обход снизу вверх)
|
||
sort.Slice(paths, func(i, j int) bool {
|
||
return len(paths[i]) > len(paths[j])
|
||
})
|
||
|
||
for _, oldPath := range paths {
|
||
info, err := os.Lstat(oldPath)
|
||
if err != nil {
|
||
fmt.Printf("[ОШИБКА] Не удалось получить информацию о %s: %v\n", oldPath, err)
|
||
continue
|
||
}
|
||
|
||
dir := filepath.Dir(oldPath)
|
||
oldName := filepath.Base(oldPath)
|
||
|
||
// 1. Проверяем, нужно ли удалить файл (папки не удаляем)
|
||
if !info.IsDir() && cfg.Filter.ShouldDelete(oldName) {
|
||
if cfg.DryRun {
|
||
fmt.Printf("[DRY-RUN УДАЛЕНИЕ] %s\n", oldPath)
|
||
continue
|
||
}
|
||
if err := os.Remove(oldPath); err != nil {
|
||
fmt.Printf("[ОШИБКА] Не удалось удалить %s: %v\n", oldPath, err)
|
||
continue
|
||
}
|
||
fmt.Printf("[УДАЛЕНО] %s\n", oldPath)
|
||
continue
|
||
}
|
||
|
||
// 2. Очищаем имя файла или папки от ключевых слов
|
||
newName := cfg.Filter.Clean(oldName, info.IsDir())
|
||
if newName == "" || newName == oldName {
|
||
continue
|
||
}
|
||
|
||
newPath := filepath.Join(dir, newName)
|
||
|
||
if _, err := os.Stat(newPath); err == nil {
|
||
fmt.Printf("[ПРОПУСК] %s -> %s (целевой объект уже существует)\n", oldPath, newName)
|
||
continue
|
||
}
|
||
|
||
if cfg.DryRun {
|
||
fmt.Printf("[DRY-RUN] %s ---> %s\n", oldPath, newName)
|
||
continue
|
||
}
|
||
|
||
if err := os.Rename(oldPath, newPath); err != nil {
|
||
fmt.Printf("[ОШИБКА] Не удалось переименовать %s: %v\n", oldPath, err)
|
||
continue
|
||
}
|
||
fmt.Printf("[OK] %s ---> %s\n", oldPath, newName)
|
||
}
|
||
|
||
return nil
|
||
}
|