common/IsDirEmpty: do not mask non-existance errors

Currently IsDirEmpty returns true, err if it encounters
any error after trying to os.Open the directory.
I noticed this while studying the code and recalled a bug
from an earlier project in which doing the exact same thing
on code without permissions would trip out and falsely report
that the directory was empty.
Given demo.go in https://play.golang.org/p/vhTPU2RiCJ

* Demo:
```shell
$ mkdir -p sample-demo/1 && touch sample-demo/2
$ echo "1st round" && go run demo.go sample-demo
$ sudo chown root sample-demo && sudo chmod 0700 sample-demo
$ echo "2nd round" && go run demo.go sample-demo
```

That then prints out
```shell
1st round
original:: empty: false err: <nil>
updated::  empty: false err: <nil>
2nd round
original:: empty: true err: open data/: permission denied
updated::  empty: false err: open data/: permission denied
```

where in "2nd round", the original code falsely reports that
the directory is empty but that's a permission error.

I could write a code test for it, but that test requires me to change
users and switch to root as a Go user so no point in complicating our
tests, but otherwise it is a 1-to-1 translation between shell and Go.
This commit is contained in:
Emmanuel Odeke 2017-08-04 02:03:46 -06:00
parent 75372988e7
commit b4a51871b9
No known key found for this signature in database
GPG Key ID: 1CA47A292F89DD40
1 changed files with 6 additions and 1 deletions

View File

@ -48,7 +48,12 @@ func EnsureDir(dir string, mode os.FileMode) error {
func IsDirEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return true, err //folder is non-existent
if os.IsNotExist(err) {
return true, err
}
// Otherwise perhaps a permission
// error or some other error.
return false, err
}
defer f.Close()