当有更改时,使git-clang-format返回错误代码

cfh9epnr  于 2023-03-21  发布在  Git
关注(0)|答案(2)|浏览(131)

git clang-format是一个很方便的工具,它可以只在git补丁所涉及的行上运行clang-format。我想阻止自己意外提交和推送我忘记运行git-clang-format的补丁。例如,通过向.git/hooks/pre-commit添加一个检查,以确保git clang-format HEAD~1没有任何事情要做。然而,它看起来并没有改变返回代码。
clang-format本身有--dry-run -WerrorCan clang-format tell me if formatting changes are necessary?
不幸的是,git-clang-format似乎不支持它,或者有一种方法可以转发参数。有没有一种编程方法可以知道是否有更改?

$ git clang-format -Werror --diff HEAD~1 -q
usage: git clang-format [OPTIONS] [<commit>] [<commit>] [--] [<file>...]
git-clang-format: error: unrecognized arguments: -Werror
brccelvz

brccelvz1#

作为一种解决方法,我检查stdout以查看--diff中是否没有更改:

# Use -q to suppress 'no changes' message and then grep for any lines printed
git clang-format --diff HEAD~1 -q | grep '^' --color=never

# Alternative: use awk to search for the 'no changes' messages and return the result
# This is a bad because the message could change in future versions
git clang-format --diff HEAD~1 | awk '/^no modified files to format|^clang-format did not modify any files/{result=1;}/^/{print} END{ exit !result}'

因为两者都使用管道,所以diff中的颜色被删除了。为了在.git/hooks/pre-commit钩子中保持输出中的颜色,我运行了两次...:(

#!/bin/bash
git clang-format --diff HEAD~1 -q
if git clang-format --diff HEAD~1 -q | grep -m 1 '^' >/dev/null; then
    echo >&2 "Failed clang-format check. Run: git clang-format HEAD~1"
    exit 1
fi
webghufk

webghufk2#

git-clang-formatnow返回错误代码% 1
您应该更新LLVM安装。

相关问题