Skip to content

Instantly share code, notes, and snippets.

@karrick
Created February 15, 2018 08:34
Show Gist options
  • Save karrick/c8f4c35ee49bae398577bb1f8b7c5b87 to your computer and use it in GitHub Desktop.
Save karrick/c8f4c35ee49bae398577bb1f8b7c5b87 to your computer and use it in GitHub Desktop.
Go function that prunes empty directories from file system hierarchy
package main
import (
"fmt"
"os"
"github.com/karrick/godirwalk"
"github.com/pkg/errors"
)
func pruneEmptyDirectories(osDirname string, scratchBuffer []byte) error {
var removedDirectoryCount int
err := godirwalk.Walk(osDirname, &godirwalk.Options{
Unsorted: true,
ScratchBuffer: scratchBuffer,
Callback: func(_ string, _ *godirwalk.Dirent) error {
return nil // no-op while diving in
},
PostChildrenCallback: func(osPathname string, _ *godirwalk.Dirent) error {
// fmt.Fprintf(os.Stderr, "# checking for empty directory: %s\n", osPathname) // DEBUG
deChildren, err := godirwalk.ReadDirents(osPathname, scratchBuffer)
if err != nil {
return errors.Wrap(err, "cannot ReadDirents")
}
// NOTE: ReadDirents skips "." and ".."
if len(deChildren) > 0 {
return nil // this directory has children; no additional work here
}
// fmt.Fprintf(os.Stderr, "# removing empty directory: %s\n", osPathname) // DEBUG
err = os.Remove(osPathname)
if err == nil {
removedDirectoryCount++
}
return err
},
})
fmt.Fprintf(os.Stderr, "# removed %d empty directories\n", removedDirectoryCount)
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment