40
filex/file.go
Normal file
40
filex/file.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package filex
|
||||
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
// IsFile Check path is a file
|
||||
func IsFile(path string) bool {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return !fi.IsDir()
|
||||
}
|
||||
|
||||
// IsDir Check path is directory
|
||||
func IsDir(path string) bool {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return fi.IsDir()
|
||||
}
|
||||
|
||||
// Exists Check path is exists
|
||||
func Exists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil || os.IsExist(err) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Size Return file size
|
||||
func Size(path string) int64 {
|
||||
if fi, err := os.Stat(path); err == nil {
|
||||
return fi.Size()
|
||||
}
|
||||
return 0
|
||||
}
|
||||
66
filex/file_test.go
Normal file
66
filex/file_test.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package filex
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsDir(t *testing.T) {
|
||||
root, _ := os.Getwd()
|
||||
testCases := []struct {
|
||||
Path string
|
||||
Except bool
|
||||
}{
|
||||
{"/a/b", false},
|
||||
{root, true},
|
||||
{root + "/file.go", false},
|
||||
{root + "/file", false},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
v := IsDir(testCase.Path)
|
||||
if v != testCase.Except {
|
||||
t.Errorf("`%s` except %v actual %v", testCase.Path, testCase.Except, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsFile(t *testing.T) {
|
||||
root, _ := os.Getwd()
|
||||
testCases := []struct {
|
||||
Path string
|
||||
Except bool
|
||||
}{
|
||||
{"/a/b", false},
|
||||
{root, false},
|
||||
{root + "/file.go", true},
|
||||
{root + "/file", false},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
v := IsFile(testCase.Path)
|
||||
if v != testCase.Except {
|
||||
t.Errorf("`%s` except %v actual %v", testCase.Path, testCase.Except, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExists(t *testing.T) {
|
||||
root, _ := os.Getwd()
|
||||
testCases := []struct {
|
||||
Path string
|
||||
Except bool
|
||||
}{
|
||||
{"/a/b", false},
|
||||
{root, true},
|
||||
{root + "/file.go", true},
|
||||
{root + "/file", false},
|
||||
{root + "/1.jpg", false},
|
||||
{"https://golang.org/doc/gopher/fiveyears.jpg", false},
|
||||
{"https://golang.org/doc/gopher/not-found.jpg", false},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
v := Exists(testCase.Path)
|
||||
if v != testCase.Except {
|
||||
t.Errorf("`%s` except %v actual %v", testCase.Path, testCase.Except, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user