Skip to content

Commit

Permalink
Add an "Exists" function to fsutil
Browse files Browse the repository at this point in the history
Exists returns true if a file or directory exist at the given path and
false if one doesn't.
  • Loading branch information
djjuhasz committed Nov 6, 2024
1 parent 5fa59f1 commit 3d188fc
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
14 changes: 14 additions & 0 deletions fsutil/fsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ func BaseNoExt(path string) string {
return base
}

// Exists returns true if a file or directory exist at path and false if one
// doesn't. If a filesystem error occurs doing the check then Exists returns
// false and the error.
func Exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

// Move moves a file or directory. It first tries to rename src to dst. If the
// rename fails due to the source and destination being on different file
// systems Move copies src to dst, then deletes src.
Expand Down
34 changes: 34 additions & 0 deletions fsutil/fsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,40 @@ func TestBaseNoExt(t *testing.T) {
}
}

func TestExists(t *testing.T) {
t.Parallel()

td := tfs.NewDir(t, "preprocessing-sfa-test",
tfs.WithDir("a", tfs.WithFile("needle", "")),
)

type test struct {
name string
path string
want bool
}
for _, tt := range []test{
{
name: "file exists",
path: td.Join("a", "needle"),
want: true,
},
{
name: "file doesn't exist",
path: td.Join("b"),
want: false,
},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

got, err := fsutil.Exists(tt.path)
assert.NilError(t, err)
assert.Equal(t, got, tt.want)
})
}
}

func TestSetFileModes(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 3d188fc

Please sign in to comment.