mirror of
https://gitee.com/johng/gf
synced 2026-06-06 02:25:47 +08:00
add IsEmpty function for gfile
This commit is contained in:
@ -404,6 +404,30 @@ func Dir(path string) string {
|
||||
return filepath.Dir(path)
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the given <path> is empty.
|
||||
// If <path> is a folder, it checks if there's any file under it.
|
||||
// If <path> 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
|
||||
|
||||
@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user