From aba251453421f5ca0bfbf2934ae76679df8ca783 Mon Sep 17 00:00:00 2001 From: bnkai <48220860+bnkai@users.noreply.github.com> Date: Mon, 17 May 2021 08:05:29 +0300 Subject: [PATCH] fix DirExists (#1388) --- pkg/utils/file.go | 10 ++++++---- pkg/utils/file_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/pkg/utils/file.go b/pkg/utils/file.go index 6ecdf2c50..09e134b4e 100644 --- a/pkg/utils/file.go +++ b/pkg/utils/file.go @@ -39,10 +39,12 @@ func FileExists(path string) (bool, error) { // DirExists returns true if the given path exists and is a directory func DirExists(path string) (bool, error) { - exists, _ := FileExists(path) - fileInfo, _ := os.Stat(path) - if !exists || !fileInfo.IsDir() { - return false, fmt.Errorf("path either doesn't exist, or is not a directory <%s>", path) + fileInfo, err := os.Stat(path) + if err != nil { + return false, fmt.Errorf("path doesn't exist <%s>", path) + } + if !fileInfo.IsDir() { + return false, fmt.Errorf("path is not a directory <%s>", path) } return true, nil } diff --git a/pkg/utils/file_test.go b/pkg/utils/file_test.go index 611ea3964..869cd2af6 100644 --- a/pkg/utils/file_test.go +++ b/pkg/utils/file_test.go @@ -1,6 +1,8 @@ package utils import ( + "io/ioutil" + "os" "path/filepath" "testing" @@ -41,3 +43,40 @@ func TestIsPathInDir(t *testing.T) { assert.Equal(tc.expected, result, "[%d] expected: %t for dir: %s; pathToCheck: %s", i, tc.expected, tc.dir, tc.pathToCheck) } } + +func TestDirExists(t *testing.T) { + type test struct { + dir string + expected bool + } + + const st = "stash_tmp" + + tmp := os.TempDir() + tmpDir, err := ioutil.TempDir(tmp, st) // create a tmp dir in the system's tmp folder + if err == nil { + defer os.RemoveAll(tmpDir) + + tmpFile, err := ioutil.TempFile(tmpDir, st) + if err != nil { + return + } + tmpFile.Close() + + tests := []test{ + {dir: tmpDir, expected: true}, // exists + {dir: tmpFile.Name(), expected: false}, // not a directory + {dir: filepath.Join(tmpDir, st), expected: false}, // doesn't exist + {dir: "\000x", expected: false}, // stat error \000 (ASCII: NUL) is an invalid character in unix,ntfs file names. + } + + assert := assert.New(t) + + for i, tc := range tests { + result, _ := DirExists(tc.dir) + assert.Equal(tc.expected, result, "[%d] expected: %t for dir: %s;", i, tc.expected, tc.dir) + } + + } + +}