mcpField
C
C++ Code Formatter

C++ Code Formatter

github.com/calcitem开发205123 次安装7 周前更新
代码仓库

关于 C++ Code Formatter

C++ Code Formatter 是一项按 Sanmill 项目规范整理 C++ 代码并检查风格的技能,支持使用项目脚本或 clang-format 处理整个项目及暂存文件。

主要功能

  1. 01按项目规则格式化 C++
  2. 02通过项目脚本格式化 Dart 文件
  3. 03使用 clang-format 检查风格
  4. 04运行可选的 cpplint 检查
  5. 05格式化 Git 暂存文件

适用场景

  1. 01修改后格式化代码
  2. 02提交前检查代码风格
  3. 03批量格式化项目源文件
  4. 04在 CI/CD 中检查格式

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/calcitem/sanmill --skill c++-code-formatter

安装后在 Claude Code 中输入/c++-code-formatter确认已加载。

详细介绍

C++ 代码格式化工具

用途

此技能可帮助格式化 Sanmill 的 C++ 代码,确保整个代码库的代码风格一致且易于维护。

使用场景

  • 修改后格式化 C++ 代码
  • 检查代码风格是否合规
  • 提交前格式化代码
  • 批量格式化项目中的 C++ 文件
  • 在 CI/CD 管道中验证代码风格

快速命令

使用项目脚本(推荐)
# Format all C++ and Dart code (will auto-commit)
./format.sh

# Format without auto-commit
./format.sh s

该脚本会格式化:

  • src/、include/、tests/ 中的所有 .h 和 .cpp 文件
  • 项目中的所有 Dart 文件
  • 使用项目的 .clang-format 配置
手动格式化
# Format single file
clang-format -i src/position.cpp

# Format multiple files
clang-format -i src/*.cpp src/*.h

# Check without modifying (dry-run)
clang-format --dry-run --Werror src/position.cpp

配置

项目配置文件
  • .clang-format - C++ 格式化规则(项目根目录)
  • CPPLINT.cfg - 代码风格检查规则
  • .editorconfig - 编辑器专属设置
查看当前配置
cat .clang-format

代码风格检查

# Check specific file with cpplint
cpplint --config=CPPLINT.cfg src/position.cpp

# The configuration file defines which checks to enable/disable

Git 集成

提交前工作流
# 1. Make code changes
# 2. Format code
./format.sh s

# 3. Review changes
git diff

# 4. If correct, commit
git add .
git commit -m "Your commit message"
仅格式化暂存文件
git diff --cached --name-only --diff-filter=ACM | \
grep -E '\.(cpp|h|cc|hpp)$' | \
xargs clang-format -i

常见问题与解决方案

1. 格式化破坏代码结构
  • 检查:验证 .clang-format 配置
  • 检查:确保 clang-format 版本与团队标准一致
  • 临时方案:在特殊代码块中使用 // clang-format off 和 // clang-format on
2. 批量格式化产生大量更改
  • 解决方案:分批格式化并分别提交
  • 标注:使用清晰的提交信息,例如 “style: Format C++ code”
  • 沟通:通知团队成员同步
3. 开发人员之间的格式冲突
  • 确保:所有人使用相同的 .clang-format 文件
  • 确保:所有人使用相同的 clang-format 版本
  • 制定:团队格式规范

最佳实践

  1. 经常格式化:每次重大更改后都进行格式化
  2. 提交前格式化:提交前务必格式化
  3. 检查格式化更改:不要不加检查就提交格式化更改
  4. 使用项目脚本:优先使用 ./format.sh,而非手动命令
  5. 单独提交格式化更改:将格式化更改与逻辑更改分开
  6. 不要手动调整格式:交由工具处理

所需工具

clang-format
# Check if installed
clang-format --version

# Install on Ubuntu/Debian
sudo apt-get install clang-format

# Install on macOS
brew install clang-format
cpplint(可选)

用于格式化之外的额外风格检查。

输出格式

格式化操作应报告:

  • ✓ 成功格式化的文件
  • ⚠ 存在风格违规的文件
  • ✗ 格式化失败的文件
  • 📊 已处理文件总数
  • 💡 风格改进建议

参考资源

  • 配置:.clang-format、CPPLINT.cfg、.editorconfig(项目根目录)
  • 格式化脚本:format.sh(项目根目录)
  • clang-format 文档:https://clang.llvm.org/docs/ClangFormat.html
  • C++ 源码位置:src/、include/、tests/

评论

支持 Markdown