简介
tokei 是一款使用 Rust 编写的高性能代码行数统计工具,能够快速准确地统计项目中各种编程语言的代码行数、注释行数和空白行数。它支持超过 200 种编程语言的识别,是了解项目代码规模和组成的首选工具。
相比传统的 cloc 和 sloccount 等工具,tokei 的执行速度快了数倍,并且能够正确处理嵌套注释、多语言混合文件等复杂场景。它还支持多种输出格式,方便集成到 CI/CD 流程中进行代码规模的持续跟踪。
安装
# macOS
brew install tokei
# Ubuntu/Debian
sudo apt install tokei
# Cargo
cargo install tokei
核心特性
- 极速统计: Rust 编写,多线程并行处理,速度远超同类工具
- 广泛支持: 支持 200+ 种编程语言和配置文件格式
- 精确识别: 正确处理嵌套注释、字符串内注释等特殊情况
- 多种输出: 支持表格、JSON、YAML、CBOR 等输出格式
- 灵活过滤: 支持按语言、目录进行排除和筛选
- Git 感知: 自动忽略
.gitignore中列出的文件
使用示例
# 统计当前项目的代码行数
tokei
# 统计指定目录
tokei ./src ./lib
# 按文件数量排序
tokei --sort files
# 按代码行数排序
tokei --sort code
# 仅统计特定语言
tokei --type Rust,Python,JavaScript
# 排除指定目录
tokei --exclude node_modules --exclude vendor
# 输出为 JSON 格式
tokei -o json > stats.json
# 显示每个文件的详细统计
tokei --files
# 对比两个项目的代码量
tokei project-a project-b
典型场景
场景一:了解陌生项目的代码构成
接手一个新项目,先用 tokei 摸清家底:
# 统计整个项目
tokei
# 输出示例(按代码量排序):
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Language Files Lines Code Comments Blanks
# TypeScript 87 6521 5203 821 497
# JSON 23 891 891 0 0
# Markdown 12 634 468 0 166
快速判断项目主力语言、测试覆盖占比、文档完善程度。
场景二:在 README 或 PR 中展示代码规模
# 生成 Markdown 表格,直接粘贴到文档
tokei --output markdown
# 只统计核心源码(排除 vendor 和测试)
tokei src/ --exclude "**/*.test.*" --exclude "**/__tests__/**"
# 对比两个分支的代码量变化(feature branch 增加了多少行)
git stash
tokei --type Rust -o json | jq '.Rust.code' > before.txt
git stash pop
tokei --type Rust -o json | jq '.Rust.code' > after.txt
echo "新增代码行:$(($(cat after.txt) - $(cat before.txt)))"
场景三:集成到 CI/CD,持续跟踪代码规模
# GitHub Actions 中记录每次 merge 后的代码量
tokei --output json > code-stats.json
cat code-stats.json | jq '{
total_lines: (.Total.lines),
code_lines: (.Total.code),
comment_ratio: ((.Total.comments / .Total.code * 100) | floor)
}'