From b4a51871b91cdae3b1e1b742fcd92ef021de7b73 Mon Sep 17 00:00:00 2001 From: Emmanuel Odeke Date: Fri, 4 Aug 2017 02:03:46 -0600 Subject: [PATCH] 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: updated:: empty: false err: 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. --- common/os.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/common/os.go b/common/os.go index 9dc81c579..c19322baa 100644 --- a/common/os.go +++ b/common/os.go @@ -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()