From 089f7c8b06175fd6227a740eeb2a2201d221c76a Mon Sep 17 00:00:00 2001 From: David Juhasz Date: Wed, 6 Nov 2024 09:34:41 -0800 Subject: [PATCH] Add an "Exists" function to fsutil Exists returns true if a file or directory exist at the given path and false if one doesn't. --- fsutil/fsutil.go | 14 ++++++++++++++ fsutil/fsutil_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/fsutil/fsutil.go b/fsutil/fsutil.go index 2621769..8b9c187 100644 --- a/fsutil/fsutil.go +++ b/fsutil/fsutil.go @@ -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. diff --git a/fsutil/fsutil_test.go b/fsutil/fsutil_test.go index e9a8b4d..09cbaca 100644 --- a/fsutil/fsutil_test.go +++ b/fsutil/fsutil_test.go @@ -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()