karrick/godirwalk

macOS: Unsorted scan is incompatible with removing files from the directory

dottedmag opened this issue · 0 comments

The following code for recursive directory removal used to work until 74f3b4a. Since that change it started to skip files under macOS (probably filesystem-specific and might be triggered under Linux too) and failing in PostChildrenCallback with ENOTEMPTY.

I am not sure this is expected behaviour, so either fixing or documenting it would be useful.

func RemoveIfExists(f string) error {
	if err := os.Remove(f); err != nil && !os.IsNotExist(err) {
		return err
	}
	return nil
}

func Rmr(dir string) error {
	err := godirwalk.Walk(dir, &godirwalk.Options{
		Callback: func(path string, de *godirwalk.Dirent) error {
			if de.IsDir() {
				// Directory itself will be removed in PostChildrenCallback
				return nil
			}
			return RemoveIfExists(path)
		},
		PostChildrenCallback: func(path string, de *godirwalk.Dirent) error {
			return RemoveIfExists(path)
		},
		Unsorted: true,
	})
	if os.IsNotExist(err) {
		return nil
	}
	return err
}