【问题标题】:git filter for clang-format with IncludeIsMainRegex带有 IncludeIsMainRegex 的 clang 格式的 git 过滤器
【发布时间】: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.cpptest_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


    【解决方案1】:

    这是因为你没有设置优先级,如果你这样设置:

    IncludeBlocks: Regroup
    IncludeCategories:
        - Regex: '^".*"'
          Priority: 1
    

    这是有效的,因为 #include "z.h" 默认为 0 优先级,如果您不将优先级放在正则表达式上,它也需要 0

    【讨论】:

      猜你喜欢
      • 2018-01-10
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多