feat: 支持通过 file.FilePaths 获取目录下所有文件,通过 file.LineCount 统计文件行数
This commit is contained in:
parent
26993d94d9
commit
0c5ff894f8
|
@ -4,6 +4,7 @@ import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PathExist 路径是否存在
|
// PathExist 路径是否存在
|
||||||
|
@ -79,3 +80,49 @@ func ReadBlockHook(filePath string, bufferSize int, hook func(data []byte)) erro
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LineCount 统计文件行数
|
||||||
|
func LineCount(filePath string) int {
|
||||||
|
file, err := os.Open(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
line := 0
|
||||||
|
reader := bufio.NewReader(file)
|
||||||
|
for {
|
||||||
|
_, isPrefix, err := reader.ReadLine()
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if !isPrefix {
|
||||||
|
line++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilePaths 获取指定目录下的所有文件路径
|
||||||
|
// - 包括了子目录下的文件
|
||||||
|
// - 不包含目录
|
||||||
|
func FilePaths(dir string) []string {
|
||||||
|
var paths []string
|
||||||
|
abs, err := filepath.Abs(dir)
|
||||||
|
if err != nil {
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
files, err := os.ReadDir(abs)
|
||||||
|
if err != nil {
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, file := range files {
|
||||||
|
fileAbs := filepath.Join(abs, file.Name())
|
||||||
|
if file.IsDir() {
|
||||||
|
paths = append(paths, FilePaths(fileAbs)...)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
paths = append(paths, fileAbs)
|
||||||
|
}
|
||||||
|
return paths
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,22 @@
|
||||||
|
package file_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/kercylan98/minotaur/utils/file"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFilePaths(t *testing.T) {
|
||||||
|
var line int
|
||||||
|
var fileCount int
|
||||||
|
for _, path := range file.FilePaths(`D:\sources\minotaur`) {
|
||||||
|
if !strings.HasSuffix(path, ".go") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Println(path)
|
||||||
|
line += file.LineCount(path)
|
||||||
|
fileCount++
|
||||||
|
}
|
||||||
|
fmt.Println("total line:", line, "total file:", fileCount)
|
||||||
|
}
|
Loading…
Reference in New Issue