-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
367 lines (303 loc) · 8.57 KB
/
main.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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package main
import (
"bufio"
"bytes"
"encoding/gob"
"errors"
"flag"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
)
// go variables
var (
fileTotal int32
lineSum int32
blankSum int32
mutex = new(sync.Mutex)
storeFormatOut []string
relativePathArr []string
bsPool = sync.Pool{New: func() interface{} { return make([]byte, 0, 128*1024) }}
)
// go const variables
var (
space = 40 // width of `file-name` column
statusWidth = 15 // width of `status` column
numberWidth = 15 // width of `line or blank number`
)
// go flag variables
var (
rootPath string // root path of directory
excludeDirs excludeDirArray // Multiple -e flags or string seperated by commas or spaces are supported
suffixName string
)
type excludeDirArray []string
// Number is a generic type for parameters.
type Number interface {
int64 | int32 | int16 | int8 | int
}
func (e *excludeDirArray) String() string {
return fmt.Sprint(*e)
}
func (e *excludeDirArray) Set(value string) error {
commaRegex := regexp.MustCompile(`,`)
commaMatched := commaRegex.MatchString(value)
spaceRegex := regexp.MustCompile(`\s`)
spaceMatched := spaceRegex.MatchString(value)
switch {
case commaMatched && spaceMatched:
return errors.New("spaces and commas cannot be included at the same time, there is only one type: `spaces` or `commas`")
case commaMatched && !spaceMatched:
commas := strings.Split(value, ",")
*e = commas
return nil
case spaceMatched && !commaMatched:
spaces := strings.Split(value, " ")
*e = spaces
return nil
default:
*e = append(*e, value)
return nil
}
}
func init() {
flag.StringVar(&rootPath, "p", ".", "Root path.")
flag.StringVar(&suffixName, "s", `.go`, "Suffix name of file, starts with `.`; Such as `.go`")
flag.Var(&excludeDirs, "e", "Exclude directories, Multiple -e flags or string seperated by commas or spaces are supported.")
flag.Parse()
}
func main() {
rootPath, err := convertToAbsPath(rootPath)
checkErr(err)
fmt.Println("root Path:", rootPath)
fmt.Println("Suffix name:", suffixName)
fmt.Printf("Exclude Dirs: %s\n\n", excludeDirs.String())
title := formatTitle(0)
storeFormatOut = append(storeFormatOut, title)
done := make(chan bool)
go codeLineSum(rootPath, done)
<-done
rSpace := getMaximumLinesNumber(relativePathArr)
if rSpace < space {
rSpace = space
}
length, newOut := formatOutput(storeFormatOut, rSpace, suffixName)
if len(newOut) == 2 {
/* Only this two lines
type |file-name |status |line[blank] |line[code]
-----------------------------------------------------------------------------------------
Do nothing.
*/
} else {
for _, v := range newOut {
fmt.Println(v)
}
fmt.Println(strings.Repeat("-", length))
}
// https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences/33206814#33206814
fmt.Printf("\033[1mSummary:\033[0m total files: \033[31m%d\033[0m blanks: \033[32m%d\033[0m codes: \033[33m%d\033[0m\n",
fileTotal, blankSum, lineSum)
}
func convertToAbsPath(root string) (path string, err error) {
path, err = filepath.Abs(root)
return path, err
}
func codeLineSum(root string, done chan bool) {
var goes int
goDone := make(chan bool)
isDstDir := excludeDir(root)
defer func() {
if pan := recover(); pan != nil {
fmt.Printf("root: %s, panic:%#v\n", root, pan)
}
for i := 0; i < goes; i++ {
<-goDone
}
done <- true
}()
if !isDstDir {
return
}
rootFileInfo, err := os.Lstat(root)
checkErr(err)
rootFile, err := os.Open(root)
checkErr(err)
defer func(rootFile *os.File) {
err := rootFile.Close()
if err != nil {
fmt.Printf("filename: %s, panic:%#v\n", root, err)
}
}(rootFile)
if rootFileInfo.IsDir() {
fis, err := rootFile.ReadDir(0)
checkErr(err)
for _, fi := range fis {
if strings.HasPrefix(fi.Name(), ".") {
continue
}
addNumWithLock(1, &goes)
if fi.IsDir() {
go codeLineSum(path.Join(root, fi.Name()), goDone)
} else {
go readFile(path.Join(root, fi.Name()), goDone)
}
}
} else {
goes = 1
go readFile(root, goDone)
}
}
func readFile(fileName string, done chan bool) {
var line, blank int32
rootPath, err := convertToAbsPath(rootPath)
checkErr(err)
isDstFile := strings.HasSuffix(fileName, suffixName)
defer func() {
if pan := recover(); pan != nil {
fmt.Printf("filename: %s, panic:%#v\n", fileName, pan)
}
if isDstFile {
addNumWithLock(line, &lineSum)
addNumWithLock(blank, &blankSum)
relativePath := strings.Split(fileName, rootPath)[1]
relativePathArr = append(relativePathArr, relativePath)
rLine := formatLine(0, relativePath, line, blank)
storeFormatOut = append(storeFormatOut, rLine)
}
done <- true
}()
if !isDstFile {
return
}
atomic.AddInt32(&fileTotal, 1)
file, err := os.Open(fileName)
checkErr(err)
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Printf("filename: %s, panic:%#v\n", fileName, err)
}
}(file)
buf := getByteSlice()
defer putByteSlice(buf)
scanner := bufio.NewScanner(file)
scanner.Buffer(buf, 1024*1024)
for scanner.Scan() {
lineOrg := scanner.Text()
lineOrgLen := len(strings.TrimSpace(lineOrg))
if lineOrgLen == 0 {
// blank lines
atomic.AddInt32(&blank, 1)
} else {
// codes and comments
atomic.AddInt32(&line, 1)
}
}
}
// excludeDir return true if the dirPath is contained in `excludeDirs`, otherwise false.
func excludeDir(dirPath string) bool {
for _, dir := range excludeDirs {
if strings.Contains(dirPath, dir) {
return false
}
}
return true
}
// addNumWithLock Adds `num` to `*sumVar` with Lock
func addNumWithLock[T Number](num T, sumVar *T) {
mutex.Lock()
defer mutex.Unlock()
*sumVar += num
}
func checkErr(err error) {
if err != nil {
panic(err.Error())
}
}
func getMaximumLinesNumber(lineArr []string) int {
var nums []int
for i := 0; i < len(lineArr); i++ {
nums = append(nums, len(lineArr[i]))
}
if len(nums) == 0 {
return 0
}
maxNum := getMaxNumber(nums)
return maxNum
}
func getMaxNumber(arr []int) int {
maxVal := arr[0]
for i := 1; i < len(arr); i++ {
if maxVal < arr[i] {
maxVal = arr[i]
}
}
return maxVal
}
func formatTitle[T Number](space T) string {
title := fmt.Sprintf(
"%s |%-"+strconv.Itoa(int(space))+"s"+"|%-"+strconv.Itoa(statusWidth)+"s"+"|%-"+strconv.Itoa(numberWidth)+"s"+"|%s\n",
"type", "file-name", "status", "line[blank]", "line[code]")
return title
}
func formatLine[T Number](space T, relativePath string, line, blank T) string {
rLine := fmt.Sprintf(
"file |%-"+strconv.Itoa(int(space))+"s"+"|%-"+strconv.Itoa(statusWidth)+"s"+"|%-"+strconv.Itoa(numberWidth)+"s"+"|line = %d\n",
relativePath, "complete", fmt.Sprintf("blank = %d", blank), line)
return rLine
}
// formatOutput format the output contents.
func formatOutput[T Number](storeOutStr []string, space T, suffixName string) (T, []string) {
var newStoreOutStr *[]string
err := deepCopy(&newStoreOutStr, storeOutStr)
checkErr(err)
(*newStoreOutStr)[0] = strings.TrimRight(formatTitle(space), "\n")
maxLength := len((*newStoreOutStr)[0])
*newStoreOutStr = append((*newStoreOutStr)[:1], append([]string{strings.Repeat("-", maxLength)}, (*newStoreOutStr)[1:]...)...)
restStoreOutStr := (*newStoreOutStr)[2:]
for i := 0; i < len(restStoreOutStr); i++ {
var err error
re, err := regexp.Compile("/(.*?)\\" + suffixName)
checkErr(err)
content := restStoreOutStr[i]
filePath := re.FindString(content)
blankCompile := regexp.MustCompile(`blank = (\d+)`)
lineCompile := regexp.MustCompile(`line = (\d+)`)
lineNum, err := strconv.Atoi(trimStringSpace(strings.Split(lineCompile.FindString(content), "=")[1], false))
checkErr(err)
blankNum, err := strconv.Atoi(trimStringSpace(strings.Split(blankCompile.FindString(content), "=")[1], false))
checkErr(err)
filePath = strings.TrimPrefix(filePath, "/")
restStoreOutStr[i] = strings.TrimRight(formatLine(space, filePath, T(lineNum), T(blankNum)), "\n")
}
return T(maxLength), *newStoreOutStr
}
func getByteSlice() []byte {
return bsPool.Get().([]byte)
}
func putByteSlice(bs []byte) {
bsPool.Put(bs)
}
// deepCopy
// dst can't be a non-pointer type.
func deepCopy(dst, src interface{}) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(src); err != nil {
return err
}
return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
}
// trimStringSpace trim all space if all is true, trim leading and trailing space otherwise.
func trimStringSpace(s string, all bool) string {
if !all {
return strings.TrimSpace(s)
} else {
return strings.ReplaceAll(s, " ", "")
}
}