如何将 clang-formatting 添加到预提交挂钩?

问题描述 投票:0回答:4

我是提交钩子和 Clang 格式的新手,并尝试将两者集成。我已经设置了预提交挂钩,并且知道如何在命令行上运行 Clang 格式,但不确定如何将其添加到文件中。

这是我在命令行中运行的用于格式化的代码:

clang-format -i -style=llvm fileName

我还尝试在所有准备提交的文件上运行此操作。

git diff --cached --name-only

这是我的

pre-commit
文件:

hook_enabled=true

# Redirect output to stderr.
exec 1>&2

# If the hook is enabled and there are one or more files added to the commit run
# code formatting.
if [ "$hook_enabled" != "false" ] &&
    test $(git diff --cached --name-only $against | wc -c) != 0
then
    cat <<\EOF
  Code formatting changed some files, please review and re-add files with git add
EOF
    exit 1

我还添加了 clang-formatting 到

package.json
:

    "pre-commit": "check-clang-format",
    "format": "git-clang-format",

请帮我整合 clang-formatting。

git clang githooks pre-commit-hook
4个回答
20
投票

现在(终于)使用开源变得非常简单https://pre-commit.com(框架):

repos:
- repo: https://github.com/pre-commit/mirrors-clang-format
  rev: v14.0.6
  hooks:
  - id: clang-format

它从 PyPI 获取适用于所有常见平台(Windows 64 和 32、macOS 通用、manylinux 64 和 32、arm、ppc 和 s390x)的 1-2 MB 二进制文件。您可以固定 clang-format 10、11 或 12(现在是 13、14 和各种补丁版本,通常是同一天发布!)。请参阅https://github.com/ssciwr/clang-format-wheel。如果您使用 https://pre-commit.ci,您将获得自动更新 PR,并且您的 PR 会自动修复。


17
投票

我将以下内容添加到我的

REPO_ROOT/.git/hooks/pre-commit
文件的顶部:

for FILE in $(git diff --cached --name-only)
do
        clang-format -i $FILE
done

.clang-format
文件放置在
REPO_ROOT
中。

另一个答案和对原始问题的第一条评论没有说明为什么最好避免使用此解决方案,所以我很高兴听到更多相关信息。


3
投票

实际上,您不会在预提交挂钩处调用 clang 格式的二进制文件。

以下是如何在预提交钩子上设置 clang 格式的说明:https://github.com/andrewseidl/githook-clang-format

安装 首先,确认
clang-format
已安装。在 Linux 上,这应该包含在常规的
clang
包中。对于

带有 Homebrew 的 MacOSX,

clang-format
可通过
brew install
  clang-format
获得。

现在将此存储库中的

clang-format.hook
安装到您的存储库中
.git/hooks
。如果您还没有预提交挂钩,您可以 只需将
clang-format.hook
复制到
.git/hooks/pre-commit
。为了 示例:

cp githook-clang-format/clang-format.hook
  myrepo/.git/hooks/pre-commit

用法 一旦安装了预提交挂钩,当您运行
clang-format
时,
git commit
将在提交中包含的每个文件上运行。

默认情况下,

clang-format
使用LLVM风格。要改变这一点,要么 创建一个
.clang-format
文件,其顶部带有您想要的格式 您的存储库级别,或设置
hooks.clangformat.style
配置选项 在你的仓库中。如果您愿意,则首选
.clang-format
文件方法 正在与团队合作或将进行任何重大定制 风格。

您可以根据您想要的样式生成

.clang-format
文件 (这里,llvm)使用:

clang-format -style=llvm -dump-config > .clang-format

要使用

git config
方法,请在您的存储库中执行以下操作:

git config hooks.clangformat.style llvm


2
投票

另一种选择(不是预提交,但也可以应用于提交)是运行

git clang-format HEAD~1 <whatever options>
。这只会影响最新提交更改的行。它会就地进行更改,因此在这种情况下不需要 -i。

© www.soinside.com 2019 - 2024. All rights reserved.