From dfc76ddb764819509e38d2d4d2eee32601fcaea8 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 5 Sep 2019 19:22:11 +0800 Subject: [PATCH] add IsEmpty function for gfile --- os/gfile/gfile.go | 24 ++++++++++++++++++++++++ os/gfile/gfile_z_test.go | 33 ++++++++++++++++++++++++++++----- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/os/gfile/gfile.go b/os/gfile/gfile.go index 9063d9b4e..73a645e3b 100644 --- a/os/gfile/gfile.go +++ b/os/gfile/gfile.go @@ -404,6 +404,30 @@ func Dir(path string) string { return filepath.Dir(path) } +// IsEmpty checks whether the given is empty. +// If is a folder, it checks if there's any file under it. +// If is a file, it checks if the file size is zero. +func IsEmpty(path string) bool { + stat, err := Stat(path) + if err != nil { + return false + } + if stat.IsDir() { + file, err := os.Open(path) + if err != nil { + return false + } + defer file.Close() + names, err := file.Readdirnames(-1) + if err != nil { + return false + } + return len(names) == 0 + } else { + return stat.Size() == 0 + } +} + // Ext returns the file name extension used by path. // The extension is the suffix beginning at the final dot // in the final element of path; it is empty if there is diff --git a/os/gfile/gfile_z_test.go b/os/gfile/gfile_z_test.go index 36dac3c5e..d96691429 100644 --- a/os/gfile/gfile_z_test.go +++ b/os/gfile/gfile_z_test.go @@ -12,6 +12,9 @@ import ( "strings" "testing" + "github.com/gogf/gf/os/gtime" + "github.com/gogf/gf/util/gconv" + "github.com/gogf/gf/os/gfile" "github.com/gogf/gf/test/gtest" ) @@ -29,6 +32,31 @@ func Test_IsDir(t *testing.T) { }) } +func Test_IsEmpty(t *testing.T) { + gtest.Case(t, func() { + path := "/testdir_" + gconv.String(gtime.Nanosecond()) + createDir(path) + defer delTestFiles(path) + + gtest.Assert(gfile.IsEmpty(testpath()+path), true) + gtest.Assert(gfile.IsEmpty(testpath()+path+gfile.Separator+"test.txt"), false) + }) + gtest.Case(t, func() { + path := "/testfile_" + gconv.String(gtime.Nanosecond()) + createTestFile(path, "") + defer delTestFiles(path) + + gtest.Assert(gfile.IsEmpty(testpath()+path), true) + }) + gtest.Case(t, func() { + path := "/testfile_" + gconv.String(gtime.Nanosecond()) + createTestFile(path, "1") + defer delTestFiles(path) + + gtest.Assert(gfile.IsEmpty(testpath()+path), false) + }) +} + func Test_Create(t *testing.T) { gtest.Case(t, func() { var ( @@ -36,20 +64,15 @@ func Test_Create(t *testing.T) { filepaths []string fileobj *os.File ) - filepaths = append(filepaths, "/testfile_cc1.txt") filepaths = append(filepaths, "/testfile_cc2.txt") - for _, v := range filepaths { fileobj, err = gfile.Create(testpath() + v) defer delTestFiles(v) fileobj.Close() gtest.Assert(err, nil) - } - }) - } func Test_Open(t *testing.T) {