Implement cleaning empty directories

This commit is contained in:
2024-01-26 16:00:30 +01:00
parent e7dc2d3f90
commit 6720e67e0b

51
main.go
View File

@@ -80,7 +80,7 @@ func scanRoot() {
if info.IsDir() { if info.IsDir() {
log.Printf("Skipping directory %s...\n", path) log.Printf("Skipping directory %s...\n", path)
return nil return filepath.SkipDir
} }
// We hope that IGNORED_DIRECTORIES is a small list, so we can afford to iterate over it // We hope that IGNORED_DIRECTORIES is a small list, so we can afford to iterate over it
@@ -89,7 +89,7 @@ func scanRoot() {
log.Println(constants.IGNORED_DIRECTORIES, len(constants.IGNORED_DIRECTORIES)) log.Println(constants.IGNORED_DIRECTORIES, len(constants.IGNORED_DIRECTORIES))
if strings.HasPrefix(path, ignoredDir) { if strings.HasPrefix(path, ignoredDir) {
log.Printf("Ignoring directory %s\n", path) log.Printf("Ignoring directory %s\n", path)
return nil return filepath.SkipDir
} }
} }
@@ -164,6 +164,51 @@ func deleteFile(path string) {
} }
} }
func cleanRoot() {
var files, err = os.ReadDir(constants.ROOT)
if err != nil {
log.Printf("Error reading root directory %s: %s\n", constants.ROOT, err)
return
}
for _, file := range files {
if !file.IsDir() {
continue
}
var empty, err = isDirEmpty(constants.ROOT + "/" + file.Name())
if err != nil {
log.Printf("Error checking if directory %s is empty: %s\n", file.Name(), err)
continue
}
log.Printf("Directory %s isempty: %t\n", file.Name(), empty)
if empty {
log.Printf("Deleting empty directory %s\n", file.Name())
var err = os.RemoveAll(constants.ROOT + "/" + file.Name())
if err != nil {
log.Printf("Error deleting empty directory %s: %s\n", file.Name(), err)
}
}
}
}
func isDirEmpty(dirPath string) (bool, error) {
var empty = true
var ferr error = nil
filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Printf("Error scanning %s: %s\n", path, err)
ferr = err
return nil
}
if !info.IsDir() {
empty = false
log.Printf("Directory %s is not empty, found %s\n", dirPath, path)
return filepath.SkipAll
}
return nil
})
return empty, ferr
}
type Constants struct { type Constants struct {
ROOT string ROOT string
ROOT_ARCHIVE string ROOT_ARCHIVE string
@@ -212,10 +257,12 @@ func main() {
scanRoot() scanRoot()
scanArchive() scanArchive()
cleanRoot()
for { for {
log.Printf("Running at %d", time.Now().UnixMilli()) log.Printf("Running at %d", time.Now().UnixMilli())
time.Sleep(SCAN_INTERVAL) time.Sleep(SCAN_INTERVAL)
scanRoot() scanRoot()
scanArchive() scanArchive()
cleanRoot()
} }
} }