一个用 Go 编写的代码圈复杂度分析工具,帮助开发者识别需要重构的复杂函数。
- ✅ 分析 Go 源代码的圈复杂度
- ✅ 支持单文件和目录扫描
- ✅ 多种输出格式(表格、JSON、纯文本)
- ✅ 可配置复杂度阈值
- ✅ 彩色终端输出
- ✅ 统计信息汇总
go install github.com/silaswei-io/cyclomatic-complexity@latest# 分析单个文件
cyclomatic-complexity main.go
# 分析整个目录
cyclomatic-complexity ./...
# 分析多个路径
cyclomatic-complexity file1.go file2.go ./pkg# 指定输出格式 (table, json, text)
cyclomatic-complexity -o json main.go
# 设置复杂度阈值(默认 10)
cyclomatic-complexity -t 15 main.go
# 组合使用
cyclomatic-complexity -o json -t 15 ./...┌──────────────┬────────────┬──────┬────────┬─────────┐
│ 文件 │ 函数 │ 行号 │ 复杂度 │ 状态 │
├──────────────┼────────────┼──────┼────────┼─────────┤
│ main.go:42 │ processData│ 42 │ 15 │ ⚠️ 过高│
│ utils.go:18 │ calculate │ 18 │ 5 │ ✅ 良好 │
└──────────────┴────────────┴──────┴────────┴─────────┘
📊 统计信息:
总函数数: 25
平均复杂度: 4.32
最大复杂度: 15
高复杂度函数: 1 ⚠️
{
"results": [
{
"file": "main.go",
"function": "processData",
"line": 42,
"complexity": 15
}
],
"summary": {
"total_functions": 25,
"average": 4.32,
"max": 15,
"high_complexity": 1
}
}main.go:42: processData - 复杂度: 15 [过高]
utils.go:18: calculate - 复杂度: 5 [良好]
| 复杂度 | 状态 | 说明 |
|---|---|---|
| 1-7 | ✅ 良好 | 代码简单易懂 |
| 8-9 | ⚡ 注意 | 建议关注,可考虑重构 |
| 10+ | 强烈建议重构 |
圈复杂度基于 McCabe 公式计算,以下结构会增加复杂度:
if语句:+1for/range循环:+1case分支:每个 +1&&和||操作符:+1select语句:+1
基础复杂度为 1(空函数)。
在 PR 审查前运行,快速识别复杂度增长:
cyclomatic-complexity -t 10 ./changed_files/在 CI 中使用,超过阈值则失败:
# exit code 1 表示有高复杂度函数
cyclomatic-complexity -t 10 ./...定期生成 JSON 报告,追踪复杂度趋势:
cyclomatic-complexity -o json ./... > complexity-$(date +%Y%m%d).json# 运行测试
go test ./...
# 测试覆盖率
go test -cover ./...分析项目代码:
$ cyclomatic-complexity ./testdata
┌───────────────────────┬──────────────────────────┬──────┬────────┬─────────┐
│ 文件 │ 函数 │ 行号 │ 复杂度 │ 状态 │
├───────────────────────┼──────────────────────────┼──────┼────────┼─────────┤
│ testdata/simple.go:65 │ HighComplexityFunction │ 65 │ 8 │ ⚡ 注意 │
│ testdata/simple.go:49 │ ComplexFunction │ 49 │ 4 │ ✅ 良好 │
│ testdata/simple.go:42 │ SwitchFunction │ 42 │ 4 │ ✅ 良好 │
│ testdata/simple.go:31 │ NestedIfFunction │ 31 │ 3 │ ✅ 良好 │
│ testdata/simple.go:23 │ ForLoopFunction │ 23 │ 2 │ ✅ 良好 │
│ testdata/simple.go:16 │ IfElseFunction │ 16 │ 2 │ ✅ 良好 │
│ testdata/simple.go:8 │ IfFunction │ 8 │ 2 │ ✅ 良好 │
│ testdata/simple.go:4 │ SimpleFunction │ 4 │ 1 │ ✅ 良好 │
└───────────────────────┴──────────────────────────┴──────┴────────┴─────────┘
📊 统计信息:
总函数数: 8
平均复杂度: 3.38
最大复杂度: 8
高复杂度函数: 0 ✅欢迎提交 Issue 和 Pull Request!
MIT License
A: 高复杂度的代码难以理解、测试和维护。研究表明,复杂度超过 10 的函数更容易出现 bug。
A: 常见方法:
- 提取函数/方法
- 使用多态替代条件判断
- 应用策略模式
- 分解大型 switch 语句
A: 一般建议:
- 10:行业标准阈值
- 15:较宽松,适合遗留代码
- 5:严格,适合新项目
Happy Coding! 🎉