Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a "Exists" function to fsutil #24

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading