From d6937a494b350dc6fdcbeba81f71f1ecfcff9e1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olive=CC=81r=20Falvai?= Date: Fri, 28 Oct 2022 13:48:54 +0200 Subject: [PATCH] Add `IsDirExists()` utility --- pathutil/pathutil.go | 9 ++++++- pathutil/pathutil_test.go | 54 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/pathutil/pathutil.go b/pathutil/pathutil.go index aaa00df..78d6aa6 100644 --- a/pathutil/pathutil.go +++ b/pathutil/pathutil.go @@ -34,6 +34,7 @@ func (pathProvider) CreateTempDir(prefix string) (dir string, err error) { // PathChecker ... type PathChecker interface { IsPathExists(pth string) (bool, error) + IsDirExists(pth string) (bool, error) } type pathChecker struct{} @@ -49,9 +50,15 @@ func (c pathChecker) IsPathExists(pth string) (bool, error) { return isExists, err } +// IsDirExists ... +func (c pathChecker) IsDirExists(pth string) (bool, error) { + info, isExists, err := c.genericIsPathExists(pth) + return isExists && info.IsDir(), err +} + func (pathChecker) genericIsPathExists(pth string) (os.FileInfo, bool, error) { if pth == "" { - return nil, false, errors.New("No path provided") + return nil, false, errors.New("no path provided") } fileInf, err := os.Lstat(pth) diff --git a/pathutil/pathutil_test.go b/pathutil/pathutil_test.go index 6ffe413..a8cfc4b 100644 --- a/pathutil/pathutil_test.go +++ b/pathutil/pathutil_test.go @@ -1,6 +1,7 @@ package pathutil import ( + "io/ioutil" "os" "os/user" "path/filepath" @@ -81,6 +82,59 @@ func Test_pathChecker_IsPathExists(t *testing.T) { } } +func Test_pathChecker_IsDirExists(t *testing.T) { + tmpDirPath := t.TempDir() + tmpFilePath := filepath.Join(t.TempDir(), "hello.txt") + require.NoError(t, ioutil.WriteFile(tmpFilePath, []byte("hello"), 0700)) + + tests := []struct { + name string + path string + want bool + wantErr bool + }{ + { + name: "path does not exists", + path: filepath.Join("this", "should", "not", "exist"), + want: false, + }, + { + name: "current dir", + path: ".", + want: true, + }, + { + name: "empty path", + path: "", + want: false, + wantErr: true, + }, + { + name: "existing file", + path: tmpFilePath, + want: false, + }, + { + name: "existing dir", + path: tmpDirPath, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := pathChecker{} + got, err := c.IsDirExists(tt.path) + + if tt.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.Equal(t, tt.want, got) + }) + } +} + func Test_pathModifier_AbsPath(t *testing.T) { currDirPath, err := filepath.Abs(".") require.NoError(t, err)