aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2018-05-20 23:43:17 +0700
committerShulhan <ms@kilabit.info>2018-05-20 23:43:17 +0700
commit94caa531044e1336153cb1ab9ee1b50d1857c8d3 (patch)
tree65df0d508565215516e7d9357edd6288826223dd
parent821b5da112648f146ec85bf74cc359906435495a (diff)
downloadbeku-94caa531044e1336153cb1ab9ee1b50d1857c8d3.tar.xz
common: add function to check if a directory is empty
-rw-r--r--common.go23
-rw-r--r--common_test.go27
2 files changed, 50 insertions, 0 deletions
diff --git a/common.go b/common.go
index f15e7b9..121ee31 100644
--- a/common.go
+++ b/common.go
@@ -15,6 +15,29 @@ import (
)
//
+// IsDirEmpty will return true if directory is not exist or empty; otherwise
+// it will return false.
+//
+func IsDirEmpty(dir string) (ok bool) {
+ d, err := os.Open(dir)
+ if err != nil {
+ ok = true
+ return
+ }
+
+ _, err = d.Readdirnames(1)
+ if err != nil {
+ if err == io.EOF {
+ ok = true
+ }
+ }
+
+ _ = d.Close()
+
+ return
+}
+
+//
// IsIgnoredDir will return true if directory start with "_" or ".", or
// equal with "vendor" or "testdata"; otherwise it will return false.
//
diff --git a/common_test.go b/common_test.go
index f504b47..7cdf9dc 100644
--- a/common_test.go
+++ b/common_test.go
@@ -8,6 +8,33 @@ import (
"github.com/shuLhan/share/lib/test"
)
+func TestIsDirEmpty(t *testing.T) {
+ cases := []struct {
+ desc string
+ path string
+ exp bool
+ }{{
+ desc: `With dir not exist`,
+ path: `testdata/notexist`,
+ exp: true,
+ }, {
+ desc: `With dir exist and not empty`,
+ path: `testdata`,
+ }, {
+ desc: `With dir exist and empty`,
+ path: `testdata/dirempty`,
+ exp: true,
+ }}
+
+ for _, c := range cases {
+ t.Log(c.desc)
+
+ got := IsDirEmpty(c.path)
+
+ test.Assert(t, "", c.exp, got, true)
+ }
+}
+
func TestIsIgnoredDir(t *testing.T) {
cases := []struct {
name string