Ensure 'not exist' errors wrap os.ErrNotExist (#3982)

* Ensure 'not exist' errors wrap os.ErrNotExist

* Update go.sum

* Use an error type to avoid changing the error's string
This commit is contained in:
Francesc Campoy
2021-06-11 09:44:59 -07:00
committed by GitHub
parent 065432e074
commit 199802a176
3 changed files with 57 additions and 6 deletions

View File

@@ -236,7 +236,7 @@ func (n *fsNode) CleanedAbs(path string) (ConfirmedDir, string, error) {
return "", "", errors.Wrap(err, "unable to clean")
}
if node == nil {
return "", "", fmt.Errorf("'%s' doesn't exist", path)
return "", "", notExistError(path)
}
if node.isNodeADir() {
return ConfirmedDir(node.Path()), "", nil
@@ -309,7 +309,8 @@ func (n *fsNode) RemoveAll(path string) error {
return err
}
if result == nil {
return fmt.Errorf("cannot find '%s' to remove it", path)
// If the path doesn't exist, no need to remove anything.
return nil
}
return result.Remove()
}
@@ -351,6 +352,9 @@ func (n *fsNode) IsDir(path string) bool {
// ReadDir implements FileSystem.
func (n *fsNode) ReadDir(path string) ([]string, error) {
if !n.Exists(path) {
return nil, notExistError(path)
}
if !n.IsDir(path) {
return nil, fmt.Errorf("%s is not a directory", path)
}
@@ -398,7 +402,7 @@ func (n *fsNode) Open(path string) (File, error) {
return nil, err
}
if result == nil {
return nil, fmt.Errorf("cannot find '%s' to open it", path)
return nil, notExistError(path)
}
if result.offset != nil {
return nil, fmt.Errorf("cannot open previously opened file '%s'", path)
@@ -423,7 +427,7 @@ func (n *fsNode) ReadFile(path string) (c []byte, err error) {
return nil, err
}
if result == nil {
return nil, fmt.Errorf("cannot find '%s' to read it", path)
return nil, notExistError(path)
}
if result.isNodeADir() {
return nil, fmt.Errorf("cannot read content from non-file '%s'", n.Path())
@@ -490,7 +494,7 @@ func (n *fsNode) Walk(path string, walkFn filepath.WalkFunc) error {
return err
}
if result == nil {
return fmt.Errorf("cannot find '%s' to walk it", path)
return notExistError(path)
}
return result.WalkMe(walkFn)
}
@@ -629,3 +633,10 @@ func (n *fsNode) Glob(pattern string) ([]string, error) {
sort.Strings(result)
return result, nil
}
// notExistError indicates that a file or directory does not exist.
// Unwrapping returns os.ErrNotExist so errors.Is(err, os.ErrNotExist) works correctly.
type notExistError string
func (err notExistError) Error() string { return fmt.Sprintf("'%s' doesn't exist", string(err)) }
func (err notExistError) Unwrap() error { return os.ErrNotExist }