Implement cleaning empty directories
This commit is contained in:
51
main.go
51
main.go
@@ -80,7 +80,7 @@ func scanRoot() {
|
||||
|
||||
if info.IsDir() {
|
||||
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
|
||||
@@ -89,7 +89,7 @@ func scanRoot() {
|
||||
log.Println(constants.IGNORED_DIRECTORIES, len(constants.IGNORED_DIRECTORIES))
|
||||
if strings.HasPrefix(path, ignoredDir) {
|
||||
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 {
|
||||
ROOT string
|
||||
ROOT_ARCHIVE string
|
||||
@@ -212,10 +257,12 @@ func main() {
|
||||
|
||||
scanRoot()
|
||||
scanArchive()
|
||||
cleanRoot()
|
||||
for {
|
||||
log.Printf("Running at %d", time.Now().UnixMilli())
|
||||
time.Sleep(SCAN_INTERVAL)
|
||||
scanRoot()
|
||||
scanArchive()
|
||||
cleanRoot()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user