Skip to content

Commit 53c27f0

Browse files
authored
Add IsDirExists() utility (#170)
1 parent 8b6caac commit 53c27f0

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

pathutil/pathutil.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ func (pathProvider) CreateTempDir(prefix string) (dir string, err error) {
3434
// PathChecker ...
3535
type PathChecker interface {
3636
IsPathExists(pth string) (bool, error)
37+
IsDirExists(pth string) (bool, error)
3738
}
3839

3940
type pathChecker struct{}
@@ -49,9 +50,15 @@ func (c pathChecker) IsPathExists(pth string) (bool, error) {
4950
return isExists, err
5051
}
5152

53+
// IsDirExists ...
54+
func (c pathChecker) IsDirExists(pth string) (bool, error) {
55+
info, isExists, err := c.genericIsPathExists(pth)
56+
return isExists && info.IsDir(), err
57+
}
58+
5259
func (pathChecker) genericIsPathExists(pth string) (os.FileInfo, bool, error) {
5360
if pth == "" {
54-
return nil, false, errors.New("No path provided")
61+
return nil, false, errors.New("no path provided")
5562
}
5663

5764
fileInf, err := os.Lstat(pth)

pathutil/pathutil_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package pathutil
22

33
import (
4+
"io/ioutil"
45
"os"
56
"os/user"
67
"path/filepath"
@@ -81,6 +82,59 @@ func Test_pathChecker_IsPathExists(t *testing.T) {
8182
}
8283
}
8384

85+
func Test_pathChecker_IsDirExists(t *testing.T) {
86+
tmpDirPath := t.TempDir()
87+
tmpFilePath := filepath.Join(t.TempDir(), "hello.txt")
88+
require.NoError(t, ioutil.WriteFile(tmpFilePath, []byte("hello"), 0700))
89+
90+
tests := []struct {
91+
name string
92+
path string
93+
want bool
94+
wantErr bool
95+
}{
96+
{
97+
name: "path does not exists",
98+
path: filepath.Join("this", "should", "not", "exist"),
99+
want: false,
100+
},
101+
{
102+
name: "current dir",
103+
path: ".",
104+
want: true,
105+
},
106+
{
107+
name: "empty path",
108+
path: "",
109+
want: false,
110+
wantErr: true,
111+
},
112+
{
113+
name: "existing file",
114+
path: tmpFilePath,
115+
want: false,
116+
},
117+
{
118+
name: "existing dir",
119+
path: tmpDirPath,
120+
want: true,
121+
},
122+
}
123+
for _, tt := range tests {
124+
t.Run(tt.name, func(t *testing.T) {
125+
c := pathChecker{}
126+
got, err := c.IsDirExists(tt.path)
127+
128+
if tt.wantErr {
129+
require.Error(t, err)
130+
} else {
131+
require.NoError(t, err)
132+
}
133+
require.Equal(t, tt.want, got)
134+
})
135+
}
136+
}
137+
84138
func Test_pathModifier_AbsPath(t *testing.T) {
85139
currDirPath, err := filepath.Abs(".")
86140
require.NoError(t, err)

0 commit comments

Comments
 (0)