有关golang的介绍请参考我的另一篇博文.
本文通过递归遍历src目录, 统计代码行数. 涉及到的知识点有:
1. 目录遍历.
2. 读取文件.
3. 使用channel进行goroutine间的通信.
4. 使用sync包进行传统的共享内存方式的同步.
5. 错误处理.
6. defer语句的使用.
在程序中有详细的注释:
// a simple go program for computing total line of souce files stored in one dir
package main
import (
"fmt"
"bufio"
"os"
"sync"
"strings"
)
var (
linesum int
mutex *sync.Mutex = new(sync.Mutex)
)
var (
// the dir where souce file stored
rootPath string = "/home/xing/Dropbox/source/go/src"
// exclude these sub dirs
nodirs [5]string = [...]string{"/bitbucket.org", "/github.com", "/goplayer", "/uniqush", "/code.google.com"}
// the suffix name you care
suffixname string = ".go"
)
func main() {
argsLen := len(os.Args)
if argsLen == 2 {
rootPath = os.Args[1]
} else if argsLen == 3 {
rootPath = os.Args[1]
suffixname = os.Args[2]
}
// sync chan using for waiting
done := make(chan bool)
go codeLineSum(rootPath, done)
<-done
fmt.Println("total line:", linesum)
}
// compute souce file line number
func codeLineSum(root string, done chan bool) {
var goes int // children goroutines number
godone := make(chan bool) // sync chan using for waiting all his children goroutines finished
isDstDir := checkDir(root)
defer func() {
if pan := recover(); pan != nil {
fmt.Printf("root: %s, panic:%#v\n", root, pan)
}
// waiting for his children done
for i := 0; i < goes; i++ {
<-godone
}
// this goroutine done, notify his parent
done <- true
}()
if !isDstDir {
return
}
rootfi, err := os.Lstat(root)
checkerr(err)
rootdir, err := os.Open(root)
checkerr(err)
defer rootdir.Close()
if rootfi.IsDir() {
fis, err := rootdir.Readdir(0)
checkerr(err)
for _, fi := range fis {
if strings.HasPrefix(fi.Name(), ".") {
continue
}
goes++
if fi.IsDir() {
go codeLineSum(root+"/"+fi.Name(), godone)
} else {
go readfile(root+"/"+fi.Name(), godone)
}
}
} else {
goes = 1 // if rootfi is a file, current goroutine has only one child
go readfile(root, godone)
}
}
func readfile(filename string, done chan bool) {
var line int
isDstFile := strings.HasSuffix(filename, suffixname)
defer func() {
if pan := recover(); pan != nil {
fmt.Printf("filename: %s, panic:%#v\n", filename, pan)
}
if isDstFile {
addLineNum(line)
fmt.Printf("file %s complete, line = %d\n", filename, line)
}
// this goroutine done, notify his parent
done <- true
}()
if !isDstFile {
return
}
file, err := os.Open(filename)
checkerr(err)
defer file.Close()
reader := bufio.NewReader(file)
for {
_, isPrefix, err := reader.ReadLine()
if err != nil {
break
}
if !isPrefix {
line++
}
}
}
// check whether this dir is the dest dir
func checkDir(dirpath string) bool {
// 判断该文件夹是否在被排除的范围之内
for _, dir := range nodirs {
if rootPath+dir == dirpath {
return false
}
}
return true
}
func addLineNum(num int) {
// 获取锁
mutex.Lock()
// defer语句在函数返回时调用, 确保锁被释放
defer mutex.Unlock()
linesum += num
}
// if error happened, throw a panic, and the panic will be recover in defer function
func checkerr(err error) {
if err != nil {
// 在发生错误时调用panic, 程序将立即停止正常执行, 开始沿调用栈往上抛, 直到遇到recover
// 对于java程序员, 可以将panic类比为exception, 而recover则是try...catch
panic(err.Error())
}
}
分享到:
相关推荐
ClOC代码统计行数(安装包)ClOC代码统计行数(安装包),ClOC代码统计行数(安装包)亲测可用!
压缩包中包含了 CodeLineCounter, hywavesoftSCounter, LineCount 三个统计工具,功能各有千秋 用于统计软件工程源代码行数,可对指定的子... 对 Windows 下和 Unix/Linux 下的源代码文件都可以正确地统计行数。
-------------------------------------------------- -----------------------------语言文件空白注释代码---------------- -------------------------------------------------- -------------降价3 8
RabbitMQ的Golang实例代码
串口服务器测试,发送与返回
一些前端和golang练习代码
Golang 代码规范,目录 基础规范 gofmt 项目目录结构 包管理器 注释 命名 错误处理 单元测试 进阶规范 在项目中不要使用相对路径引入包,要用绝对路径 声明slice 非空slice检查 ......
使用Golang 搭建http web服务器
2.1.7 使用Golang实现万人同服的游戏服务器@袁锋峰.pdf
Go入门学习的一组示例golang代码
配置好数据库,和表名以及生成目录,可以自动生成Model文件,可以自己修改或者,配置好以后运行codegen_test.go
taker - 处理异步Golang库代码
用 500 行 Golang 代码实现高性能的消息回调中间件
统计信息的使用就像醉了我们一样。Stats-Golang统计信息包一个经过良好测试的综合性Golang统计信息库/程序包/模块,没有依赖项。 如果您有任何建议,问题或错误报告,请提出一个问题,我们将尽力为您服务。 此外,只...
GoQL - 用类似的SQL查询golang源代码
TIM系统源代码 作者自己说支持100w级别的并发。 个人认为作为golang项目实战学习肯定是OK的
golang代码提示gocode代码(github下载)
go 中的 cgo 模块可以让 go 无缝调用 c 或者 c++ 的代码,而 python 本身就是个 c 库,自然也可以由 cgo 直接调用,前提是指定正确的编译条件,如 Python.h 头文件(),以及要链接的库文件。本文以 Ubuntu 18.04 ...
目录网盘文件永久链接 project.zip 第l章课程介绍.a 第2章并发栏型Tan 第3章Go的协程rar ...第9章统计系统之统计逻辑,rar 第10统计系统之存储器rar 第11章据可视化证 第12直企业级解方客暴果程总结