From fd80bb526e7331044d4d206b0784fc88f78f309a Mon Sep 17 00:00:00 2001 From: Ettore Di Giacinto Date: Tue, 9 Feb 2021 16:51:03 +0100 Subject: [PATCH] Add DirectoryIsEmpty --- pkg/helpers/file.go | 15 +++++++++++++++ pkg/helpers/file_test.go | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/pkg/helpers/file.go b/pkg/helpers/file.go index deece2ec..81f8e8b9 100644 --- a/pkg/helpers/file.go +++ b/pkg/helpers/file.go @@ -16,6 +16,7 @@ package helpers import ( + "io" "io/ioutil" "os" "path/filepath" @@ -82,6 +83,20 @@ func ListDir(dir string) ([]string, error) { return content, err } +// DirectoryIsEmpty Checks wether the directory is empty or not +func DirectoryIsEmpty(dir string) (bool, error) { + f, err := os.Open(dir) + if err != nil { + return false, err + } + defer f.Close() + + if _, err = f.Readdirnames(1); err == io.EOF { + return true, nil + } + return false, nil +} + // Touch creates an empty file func Touch(f string) error { _, err := os.Stat(f) diff --git a/pkg/helpers/file_test.go b/pkg/helpers/file_test.go index e8d08aef..8e3366c5 100644 --- a/pkg/helpers/file_test.go +++ b/pkg/helpers/file_test.go @@ -33,6 +33,23 @@ var _ = Describe("Helpers", func() { }) }) + Context("DirectoryIsEmpty", func() { + It("Detects empty directory", func() { + testDir, err := ioutil.TempDir(os.TempDir(), "test") + Expect(err).ToNot(HaveOccurred()) + defer os.RemoveAll(testDir) + Expect(DirectoryIsEmpty(testDir)).To(BeTrue()) + }) + It("Detects directory with files", func() { + testDir, err := ioutil.TempDir(os.TempDir(), "test") + Expect(err).ToNot(HaveOccurred()) + defer os.RemoveAll(testDir) + err = Touch(filepath.Join(testDir, "foo")) + Expect(err).ToNot(HaveOccurred()) + Expect(DirectoryIsEmpty(testDir)).To(BeFalse()) + }) + }) + Context("Orders dir and files correctly", func() { It("puts files first and folders at end", func() { testDir, err := ioutil.TempDir(os.TempDir(), "test")