mcpField
C
cpp-include-sorter

cpp-include-sorter

github.com/openharmonyinsight开发3591 次安装11 周前更新
代码仓库

关于 cpp-include-sorter

用于 C/C++ 项目的代码整理技能,通过按类别排序 include 并处理条件编译块来统一头文件布局,同时保留注释并验证数量。

主要功能

  1. 01按对应头文件、系统头文件和本地头文件分组
  2. 02条件编译块作为整体参与排序
  3. 03条件块内头文件分别排序
  4. 04保留注释并校验头文件数量
  5. 05支持预览而不修改文件

适用场景

  1. 01整理目录中的 C/C++ 源文件
  2. 02规范含 #ifdef 和 #else 的头文件
  3. 03排序前预览改动
  4. 04检查整理过程是否遗漏头文件

安装

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

$npx skills add https://github.com/openharmonyinsight/openharmony-skills --skill cpp-include-sorter

安装后在 Claude Code 中输入/cpp-include-sorter确认已加载。

附带文件scripts/sort_includes.py

详细介绍

C/C++ 头文件排序器

自动对 C/C++ 源文件中的 #include 语句进行排序,并智能处理条件编译块。

快速开始

对目录中的所有 .cpp 文件进行排序:

python scripts/sort_includes.py <directory-path>

预览更改,但不修改文件:

python scripts/sort_includes.py <directory-path> --dry-run

排序规则

头文件分为 3 类,每组之间空一行:

  1. 对应头文件 - 对于 file.cpp,优先放置 file.h(如果存在重复项,则优先选择路径最长的项)
  2. 系统头文件 - 使用尖括号 <> 的头文件(按字母顺序排序)
  3. 本地头文件 - 使用双引号 "" 的头文件(按字母顺序排序)
条件编译块

#ifdef/#ifndef/#if defined 块会作为整体处理:

  • 根据块中的第一个头文件参与全局排序
  • 每个块内部的头文件也会排序(先系统头文件,再本地头文件)
  • 保留块结构(#ifdef...#endif)
  • 支持 #elif 和 #else 块

示例

之前:

#include "common/rs_log.h"
#include "rs_trace.h"
#include <memory>
#ifdef RS_ENABLE_GPU
#include "feature/uifirst/rs_sub_thread_manager.h"
#include "feature/capture/rs_ui_capture_task_parallel.h"
#endif
#include "platform/common/rs_system_properties.h"

之后:

#include "rs_trace.h"        // 1. Corresponding header (longest path preferred)

#include <memory>             // 2. System headers (alphabetical)

#include "common/rs_log.h"    // 3. Local headers (alphabetical)
#ifdef RS_ENABLE_GPU
#include "feature/capture/rs_ui_capture_task_parallel.h"
#include "feature/uifirst/rs_sub_thread_manager.h"
#endif
#include "platform/common/rs_system_properties.h"

功能

  • 重复头文件处理:当多个头文件具有相同文件名但路径不同(例如 "file.h" 和 "path/to/file.h")时,会将路径最长的项作为对应头文件并放在首位
  • 保留注释:保留行内注释(// comment)和前置注释
  • 嵌套条件编译块:处理 #ifdef 块内的 #elif 和 #else
  • 验证:确保排序过程中没有丢失头文件

脚本参考

实现详情请参阅 scripts/sort_includes.py。

关键函数:

  • extract_includes_with_ifdef() - 解析头文件和条件编译块
  • sort_includes_with_ifdef() - 按 3 类规则排序
  • format_ifdef_block() - 格式化包含已排序头文件的条件编译块

验证

排序后,请验证:

  1. 所有 #ifdef 块包含的头文件数量与排序前相同
  2. 对应头文件具有完整路径(未被缩短)
  3. 头文件总数未发生变化
  4. 注释得到保留

使用 git diff 比较前后差异:

git diff <file.cpp> | grep "^[-+]" | grep "include"

评论

支持 Markdown