dedupe/files/cleaner.go

55 lines
1.4 KiB
Go

package files
import (
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"velvettear/dedupe/log"
)
var subdirectories []string
// exported function(s)
func RemoveEmptyDirectories(directory string) {
subdirectories = nil
timestamp := time.Now()
log.Info("deleting empty subdirectories...", "directory: "+directory)
filepath.WalkDir(directory, collectSubdirectories)
sort.Slice(subdirectories, func(i, j int) bool {
return strings.Count(subdirectories[i], string(os.PathSeparator)) > strings.Count(subdirectories[j], string(os.PathSeparator))
})
count := 0
for _, subdirectory := range subdirectories {
files, error := os.ReadDir(subdirectory)
if error != nil {
log.Error("encountered an error checking the content of directory '" + subdirectory)
}
if len(files) > 0 {
continue
}
error = os.Remove(subdirectory)
if error != nil {
log.Warning("encountered an error deleting directory '"+subdirectory+"'", error.Error())
continue
}
count++
log.Debug("deleted directory '" + subdirectory + "'")
}
log.InfoTimed("finished deleting "+strconv.Itoa(count)+" empty subdirectoies", timestamp.UnixMilli(), "directory: "+directory)
}
// unexported function(s)
func collectSubdirectories(path string, dir fs.DirEntry, err error) error {
if err != nil {
return err
}
if !dir.IsDir() {
return nil
}
subdirectories = append(subdirectories, path)
return nil
}