From d2c3493d683ff36b1cc6ff9beeb3535b8f01f745 Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Sun, 5 May 2024 16:53:03 +0200 Subject: [PATCH] fix: fix IsDirEmpty and add tests (#76) --- file/dir.go | 6 ++--- file/dir_test.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 file/dir_test.go diff --git a/file/dir.go b/file/dir.go index bad83d5..f24f4fd 100644 --- a/file/dir.go +++ b/file/dir.go @@ -32,8 +32,8 @@ func IsDir(path string) (bool, error) { return false, err } -// IsDirEmpty returns whether the given directory path is empty. -// If the path does not exist or is not a directory, it returns (false, err). +// IsDirEmpty checks if the directory at the given path is empty. +// It returns true if the directory is empty, false if not empty, or an error if there was a problem checking it. func IsDirEmpty(path string) (bool, error) { f, err := os.Open(path) if err != nil { @@ -43,7 +43,7 @@ func IsDirEmpty(path string) (bool, error) { _, err = f.Readdir(1) if err == nil { - return true, nil + return false, nil } if errors.Is(err, io.EOF) { diff --git a/file/dir_test.go b/file/dir_test.go new file mode 100644 index 0000000..60329f6 --- /dev/null +++ b/file/dir_test.go @@ -0,0 +1,69 @@ +package file + +import ( + "errors" + "io/fs" + "os" + "path/filepath" + "testing" +) + +func TestIsDirEmpty(t *testing.T) { + t.Run("empty directory", func(t *testing.T) { + dir, err := os.MkdirTemp("", "test") + if err != nil { + t.Fatalf("failed to create temp dir: %v", err) + } + defer os.RemoveAll(dir) + + isEmpty, err := IsDirEmpty(dir) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + + if !isEmpty { + t.Error("expected directory to be empty") + } + }) + + t.Run("non-empty directory", func(t *testing.T) { + dir, err := os.MkdirTemp("", "test") + if err != nil { + t.Fatalf("failed to create temp dir: %v", err) + } + defer os.RemoveAll(dir) + + file, err := os.CreateTemp(dir, "test") + if err != nil { + t.Fatalf("failed to create temp file: %v", err) + } + + file.Close() + + isEmpty, err := IsDirEmpty(dir) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + + if isEmpty { + t.Error("expected directory to be non-empty") + } + }) + + t.Run("non-existent directory", func(t *testing.T) { + dir := filepath.Join(os.TempDir(), "non-existent") + + isEmpty, err := IsDirEmpty(dir) + if err == nil { + t.Error("expected an error for non-existent directory") + } + + if isEmpty { + t.Error("expected directory to be non-empty") + } + + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("unexpected error: %v", err) + } + }) +}