Last active
December 12, 2017 16:05
-
-
Save jwreagor/cbe1621bc1f43986b4522054b0415642 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// RemoveAll removes path and any children it contains. | |
// It removes everything it can but returns the first error | |
// it encounters. If the path does not exist, RemoveAll | |
// returns nil (no error). | |
func RemoveAll(path string) error { | |
// Simple case: if Remove works, we're done. | |
err := Remove(path) | |
if err == nil || IsNotExist(err) { | |
return nil | |
} | |
// Otherwise, is this a directory we need to recurse into? | |
dir, serr := Lstat(path) | |
if serr != nil { | |
if serr, ok := serr.(*PathError); ok && (IsNotExist(serr.Err) || serr.Err == syscall.ENOTDIR) { | |
return nil | |
} | |
return serr | |
} | |
if !dir.IsDir() { | |
// Not a directory; return the error from Remove. | |
return err | |
} | |
// Directory. | |
fd, err := Open(path) | |
if err != nil { | |
if IsNotExist(err) { | |
// Race. It was deleted between the Lstat and Open. | |
// Return nil per RemoveAll's docs. | |
return nil | |
} | |
return err | |
} | |
// Remove contents & return first error. | |
err = nil | |
for { | |
names, err1 := fd.Readdirnames(100) | |
for _, name := range names { | |
err1 := RemoveAll(path + string(PathSeparator) + name) | |
if err == nil { | |
err = err1 | |
} | |
} | |
if err1 == io.EOF { | |
break | |
} | |
// If Readdirnames returned an error, use it. | |
if err == nil { | |
err = err1 | |
} | |
if len(names) == 0 { | |
break | |
} | |
} | |
// Close directory, because windows won't remove opened directory. | |
fd.Close() | |
// Remove directory. | |
err1 := Remove(path) | |
if err1 == nil || IsNotExist(err1) { | |
return nil | |
} | |
if err == nil { | |
err = err1 | |
} | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment