【问题标题】:How do I add clang-formatting to pre-commit hook?如何将 clang-formatting 添加到预提交挂钩?
【发布时间】:2019-09-21 18:12:19
【问题描述】:

我是提交钩子和 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格式添加到package.json

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

请帮我整合 clang 格式。

【问题讨论】:

标签: git clang githooks pre-commit-hook


【解决方案1】:

我将以下内容添加到我的 REPO_ROOT/.git/hooks/pre-commit 文件的顶部:

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

.clang-format 文件放在REPO_ROOT 中。

原始问题的另一个答案和第一条评论没有说明为什么最好避免这种解决方案,所以我很乐意听到更多关于这个的信息。

【讨论】:

  • 为扩展添加文件管理器很有用 - if [[ "$FILE" =~ \.(c|h|cpp|cc)$ ]]; then 否则各种文件将被“格式化”
  • 这可能会破坏带有空格的文件名。
  • 在我的一生中,如果不明确调用 grep,我无法让正则表达式工作:for FILE in $(git diff --cached --name-only | grep -E '.*\.(c|cpp|h|hpp)')
【解决方案2】:

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

这里是如何在 pre-commit hook 中设置 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

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

默认情况下,clang-format 使用 LLVM 样式。要改变这一点,要么 在顶部创建一个具有所需格式的.clang-format 文件 您的仓库级别,或设置 hooks.clangformat.style 配置选项 在你的回购中。如果您愿意,首选.clang-format 文件方法 正在与团队合作或将进行任何重大定制 风格。

您可以根据您想要的样式生成.clang-format 文件 (这里,llvm)使用:

clang-format -style=llvm -dump-config &gt; .clang-format

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

git config hooks.clangformat.style llvm

【讨论】:

  • "实际上,您不会在预提交挂钩处调用 clang 格式的二进制文件。"这只是一个在预提交挂钩中调用 clang-format 的脚本。
【解决方案3】:

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

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

它从 PyPI 中为所有常见平台抓取一个 1-2 MB 的二进制文件。您可以固定 clang 格式 10、11 或 12(现在是 13,当天发布!)。见https://github.com/ssciwr/clang-format-wheel。如果您使用https://pre-commit.ci,您将获得自动更新 PR,并且您的 PR 会自动修复。

【讨论】:

    【解决方案4】:

    另一种选择(不是预先提交,但也可以申请提交)是运行git clang-format HEAD~1 &lt;whatever options&gt;。这只会影响最新提交更改的行。它会进行适当的更改,因此在这种情况下不需要 -i。

    【讨论】:

    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 2016-10-16
    • 2020-08-15
    • 2012-08-23
    • 2019-06-02
    • 2015-04-20
    • 1970-01-01
    相关资源
    最近更新 更多