-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
236 lines (201 loc) · 4.78 KB
/
main.go
File metadata and controls
236 lines (201 loc) · 4.78 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main
import (
"errors"
"flag"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
"github.com/GoToUse/treeprint"
)
// 存储大小之间的单位
const unit = 1024
// command line arguments
var (
// 目标地址
folderPath string
// 排除在外的地址数组
excludeDirArray excludeDirs
// 是否输出size
humanRead bool
// 是否部分匹配
partialMatch bool
// add lock
lock sync.Mutex
)
// global variable
var (
tp = treeprint.New()
folders int32
files int32
)
type excludeDirs []string
func (e *excludeDirs) String() string {
return fmt.Sprint(*e)
}
// multiExists check if there are more than `multi` bool values in the evalArray.
func multiExists(evalArray []bool, multi int) bool {
var n int
for _, _b := range evalArray {
if _b {
n++
}
}
if n > multi {
return true
}
return false
}
func (e *excludeDirs) Set(value string) error {
commaRegex := regexp.MustCompile(`,`)
commaMatched := commaRegex.MatchString(value)
spaceRegex := regexp.MustCompile(`\s`)
spaceMatched := spaceRegex.MatchString(value)
semicolonRegex := regexp.MustCompile(`;`)
semicolonMatched := semicolonRegex.MatchString(value)
switch {
case multiExists([]bool{commaMatched, spaceMatched, semicolonMatched}, 1):
return errors.New("spaces and commas and semicolons cannot be included at the same time, " +
"there is only one type: `spaces` or `commas` or `semicolons`")
case commaMatched:
commas := strings.Split(value, ",")
*e = commas
return nil
case spaceMatched:
spaces := strings.Split(value, " ")
*e = spaces
return nil
case semicolonMatched:
semicolons := strings.Split(value, ";")
*e = semicolons
return nil
default:
*e = append(*e, value)
return nil
}
}
// convertToAbsPath convert a passed in path to an absolute path.
func convertToAbsPath(root string) (path string, err error) {
path, err = filepath.Abs(root)
return path, err
}
func folderInExcludeArrays(subDir os.DirEntry) bool {
if subDir.IsDir() {
name := subDir.Name()
for _, dir := range excludeDirArray {
// This will exclude all `dir`s whose names are included in `name`.
if partialMatch && strings.Contains(name, dir) {
return true
} else if name == dir {
return true
}
}
}
return false
}
func catchError() {
err := recover()
if err != nil {
e := fmt.Errorf("error: %v", err)
fmt.Println(e.Error())
return
}
}
func calc(entry fs.DirEntry, wg *sync.WaitGroup, folder string, total *int64, tree treeprint.Tree) {
defer wg.Done()
if entry.IsDir() {
size, err := Parallel(path.Join(folder, entry.Name()), tree)
defer catchError()
if err != nil {
panic(err)
}
atomic.AddInt32(&folders, 1)
atomic.AddInt64(total, size)
return
}
info, err := entry.Info()
defer catchError()
if err != nil {
panic(err)
}
size := info.Size()
atomic.AddInt32(&files, 1)
atomic.AddInt64(total, size)
lock.Lock()
if humanRead {
tree.AddNode(fmt.Sprintf("%s (%s)", entry.Name(), ByteCountIEC(size)))
} else {
tree.AddNode(entry.Name())
}
lock.Unlock()
}
// Parallel execution, fast enough
func Parallel(folder string, tree treeprint.Tree) (total int64, e error) {
var wg sync.WaitGroup
entryS, err := os.ReadDir(folder)
// Do not record the size of directory.
var branch treeprint.Tree
if folder == folderPath {
branch = tree
} else {
baseFolder := path.Base(folder)
branch = tree.AddBranch(baseFolder)
}
if err != nil {
return 0, err
}
entrySLen := len(entryS)
if entrySLen == 0 {
return 0, nil
}
// wg.Add(entrySLen)
for i := 0; i < entrySLen; i++ {
subFolder := entryS[i]
if !folderInExcludeArrays(subFolder) {
wg.Add(1)
go calc(subFolder, &wg, folder, &total, branch)
}
}
wg.Wait()
return total, nil
}
// ByteCountIEC is based on 1024, converts the bytes to corresponding units such as KB.
func ByteCountIEC(b int64) string {
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f%ciB",
float64(b)/float64(div), "KMGTPE"[exp])
}
func init() {
flag.StringVar(&folderPath, "f", ".", "Folder path.")
flag.Var(&excludeDirArray, "e", "Exclude directories.")
flag.BoolVar(&humanRead, "h", false, "Print the size in a more human readable way.")
flag.BoolVar(&partialMatch, "p", false, "Support partial match.")
}
func main() {
flag.Parse()
size, err := Parallel(folderPath, tp)
defer catchError()
if err != nil {
panic(err)
}
rootPath, err := convertToAbsPath(folderPath)
defer catchError()
if err != nil {
panic(err)
}
for _, d := range []string{rootPath, tp.String(), fmt.Sprintf("\033[1mSummary:\033[0m Total folders: \033[31m%d\033[0m Total files: \033[32m%d\033[0m Total size: \033[34m%s\033[0m", folders, files, ByteCountIEC(size))} {
fmt.Println(d)
}
}