-
Notifications
You must be signed in to change notification settings - Fork 3
/
info.go
executable file
·110 lines (97 loc) · 2.67 KB
/
info.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package fileKit
import (
"github.com/gogf/gf/v2/os/gfile"
"os"
"path/filepath"
)
var (
Exists func(path string) bool = gfile.Exists
IsFile func(path string) bool = gfile.IsFile
IsDir func(path string) bool = gfile.IsDir
// Stat 获取文件(或目录)信息
/*
@param path 如果为""或不存在,将返回error(e.g."" => stat : no such file or directory)
*/
Stat func(path string) (os.FileInfo, error) = gfile.Stat
// 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.
Note that it returns true if `path` does not exist.
*/
IsEmpty func(path string) bool = gfile.IsEmpty
// GetFileName 获取 文件名.
/*
e.g.
/var/www/file.js -> file.js
file.js -> file.js
*/
GetFileName func(path string) string = filepath.Base
// GetName 获取 文件名的前缀.
/*
e.g.
/var/www/file.js -> file
file.js -> file
*/
GetName func(path string) string = gfile.Name
// GetExt 获取 文件名的后缀(带".")
/*
@return 可能为""
e.g.
println(fileKit.GetExt("main.go")) // ".go"
println(fileKit.GetExt("api.json")) // ".json"
println(fileKit.GetExt("")) // ""
println(fileKit.GetExt(" ")) // ""
println(fileKit.GetExt("empty")) // ""
*/
GetExt func(path string) string = gfile.Ext
// GetExtName 获取 后缀(不带".")
/*
@return 可能为""
e.g.
println(fileKit.GetExtName("main.go")) // "go"
println(fileKit.GetExtName("api.json")) // "json"
println(fileKit.GetExtName("")) // ""
println(fileKit.GetExtName(" ")) // ""
println(fileKit.GetExtName("empty")) // ""
*/
GetExtName func(path string) string = gfile.ExtName
)
// GetSize 获取文件(或目录)的大小.
func GetSize(path string) (int64, error) {
if err := AssertExist(path); err != nil {
return 0, err
}
if IsFile(path) {
return getFileSize(path)
}
return getDirSize(path)
}
// getFileSize 获取文件的大小.
func getFileSize(filePath string) (int64, error) {
info, err := os.Stat(filePath)
if err != nil {
return 0, err
}
return info.Size(), nil
}
// getDirSize 获取目录的大小(包含其内文件和目录).
/*
参考:
golang获取文件/目录(包含下面的文件)的大小
https://blog.csdn.net/n_fly/article/details/117080173
*/
func getDirSize(dirPath string) (int64, error) {
var bytes int64
err := filepath.Walk(dirPath, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
bytes += info.Size()
}
// 如果 err != nil,将中止遍历
return err
})
if err != nil {
return 0, err
}
return bytes, nil
}