golang写个小工具练练手
https://github.com/beckbikang/go-mfind
a find tool write in golang we can use it find some file
一个简单的文本查找工具
简单的思路:
1 扫描所有的文件
2 多协程判断文件是否符合要求
DONE
1 find filename from a dirpath
TODO
1 just find filename 2 just find dirname 3 find file by size 4 find file by type 5 list more file info
mfinder.go
package finder
import (
"fmt"
"io/IoUtil"
"os"
"runtime"
"strings"
)
type Mfinder struct {
DirPath string //查找的路径
FindName string //查找的文件名中含有的字段
MaxFileSize uint64 //文件的最大
MinFileSize uint64 //文件的最小
listFiles []string //文件列表
HasDir bool //是否包含dir
}
//初始化
func NewMfinderSimple(dirpath,filename string) *Mfinder {
return &Mfinder{DirPath: dirpath,FindName: filename,HasDir: true}
}
//获取列表
func (mf *Mfinder) GetListFiles() []string {
return mf.listFiles
}
//获取文件列表
func (mf *Mfinder) ListDir(dirPth string) (err error) {
dirSlice,err := IoUtil.ReadDir(dirPth)
if err != nil {
return err
}
PthSep := string(os.PathSeparator)
for _,filename := range dirSlice {
curFile := dirPth + PthSep + filename.Name()
if filename.IsDir() {
if mf.HasDir {
mf.listFiles = append(mf.listFiles,curFile)
}
mf.ListDir(curFile)
} else {
mf.listFiles = append(mf.listFiles)
}
}
return nil
}
//查找符合要求的文件
func (mf *Mfinder) GetRet(list []string,aChan chan []string) {
aSlice := make([]string, 100)
for _,v := range list {
if mf.checkFindRet(v) {
aSlice = append(aSlice,v)
}
}
aChan <- aSlice
}
//是否含有子串
func (mf *Mfinder) checkFindRet(path string) bool {
flag := false
flag = strings.Contains(path,mf.FindName)
return flag
}
//获取
func (mf *Mfinder) Run() {
//利用cpu的多核心
cpu_NUMS := runtime.Numcpu()
runtime.GOMAXPROCS(cpu_NUMS)
//获取文件列表
mf.ListDir(mf.DirPath)
listData := mf.GetListFiles()
//文件查找
aListLen := len(listData)
step := (int)(aListLen / cpu_NUMS)
//分配新的slice
newSlice := make([][]string,cpu_NUMS)
//创建携程
chanArr := make([]chan []string,cpu_NUMS)
//运行代码
for i := 0; i < cpu_NUMS; i++ {
chanArr[i] = make(chan []string)
newSlice[i] = listData[(i * step):(i*step + step)]
go mf.GetRet(newSlice[i],chanArr[i])
}
//打印找到的文件
strList := make([]string, 30)
for _,v := range chanArr {
values := <-v
for _,v1 := range values {
if len(v1) == 0 {
continue
}
fmt.Println(v1)
strList = append(strList,v1)
}
}
}
main.go 文件
package main
import (
"finder"
"flag"
"fmt"
"log"
"os"
)
var Usage = func() {
fmt.Println("USAGE: mfind command [arguments] ...")
fmt.Println("\nThe commands are:\n\tpath\t add file path.\n\tfilename\tthe filename to be matched.")
}
func main() {
//目录路径
var dirpath string
flag.StringVar(&dirpath,"path","","dir path")
if dirpath == "." {
newPath,err := os.Getwd()
dirpath = newPath
if err != nil {
log.Fatal("get current dir path faild\n")
}
}
//要查找的文件名
var filename string
flag.Parse()
fmt.Println(dirpath,filename)
if len(dirpath) > 0 && len(filename) > 0 {
mf := finder.NewMfinderSimple(dirpath,filename)
mf.Run()
} else {
Usage()
}
}