代码行数统计

使用gocloc工具进行统计

先介绍一款工具,gocloc。它是用Go语言写的一个快速的代码行数统计工具。使用方式很简单,首先通过命令安装gocloc$ go get -u github.com/hhatto/gocloc/cmd/gocloc,接着使用命令$ gocloc [目录路径或文件路径]即可完成统计。例如:

D:\gotest>gocloc .
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Go                              38            252            203           1257
XML                              4              0              0            629
HTML                             2              8              0             71
Protocol Buffers                 1              4              0             11
YAML                             1              0              0              9
Plain Text                       1              0              0              1
-------------------------------------------------------------------------------
TOTAL                           47            264            203           1978
-------------------------------------------------------------------------------

gocloc会按类别统计路径下有多少文件,文件中的空行数,注释行数以及实际代码行数。如果目录下某类文件不需要统计,可以使用参数--exclue-ext=[文件后缀],例如:gocloc --exclue-ext=txt .

使用git进行统计

如果你的代码是放在git仓库,那么可以通过下面的命令来统计git上提交的代码。例如:

git log --author="benben_2015" --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }' -

统计有多少次提交记录,可以组合git logwc -l命令,例如$ git log | wc -l

通过go程序实现

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	lineSum, err := readLine("./test.go")
	if err != nil {
		fmt.Println("readLine error: ", err)
		return
	}
	fmt.Println("lineSum is ", lineSum)
}

func readLine(filename string) (lineSum int, err error) {
	file, err := os.Open(filename)
	if err != nil {
		return
	}

	reader := bufio.NewReader(file)
	for {
		_, isPrefix, err := reader.ReadLine()
		if err != nil {
			break
		}
		if !isPrefix {
			lineSum++
		}
	}
	return
}

上面代码只是实现了统计单个.go文件,后面会附上统计整个目录以及更多功能的统计。
参考文章

  1. git代码统计

你可能感兴趣的:(GO学习总结)