【发布时间】:2020-07-11 04:22:23
【问题描述】:
我想在每次签入 git 存储库中任何已编辑的 .cpp 和 .h 文件时运行 clang-format,并确保“主包含文件”位于顶部。
在.gitattributes中有a filter option:
*.cpp filter=clang-format-cpp
*.h filter=clang-format-cpp
可以在本地配置相关过滤器
git config --global filter.clang-format-cpp.clean 'clang-format -assume-filename=test.cpp'
对于 clang 格式,there is an option IncludeIsMainRegex 将始终将“主包含文件”放在顶部。例如。 IncludeIsMainRegex: '(test_?)?$' 用于文件 a.cpp 或 test_a.cpp,标题 a.h 将是主要包含,因此放在顶部。
但是,当文件通过 git filter/clang-format 格式化时,这个 main include 不会放在最上面。
给定
.clang 格式:
IncludeIsMainRegex: '(test_?)?$'
IncludeBlocks: Regroup
z.cpp:
#include "z.h"
#include "other.h"
#include <includes.h>
#include <here.h>
预期
z.cpp:
#include "z.h"
#include "other.h"
#include <here.h>
#include <includes.h>
结果
z.cpp:
#include "other.h"
#include "z.h"
#include <here.h>
#include <includes.h>
原因很可能是文件是通过带有 stdin/stdout 的 clang-format 发送的,因此 clang-format 不知道文件名(或者更确切地说假设它是 test.cpp),因此无法确定主要包含。
另一种方法是设置一个预提交挂钩,并让它在提交时更正文件。但是在暂存时纠正它们比在提交时要简化得多。
如何将 clang-format 集成到 git 工作流中以自动将主包含文件放在顶部?
现在我只是禁用了IncludeIsMainRegex: false,不管clang-format是在文件上调用还是通过git过滤器调用,它都能稳定工作。
【问题讨论】:
标签: c++ git clang-format