【问题标题】:Make git-clang-format return an error code when there are changes使 git-clang-format 在有更改时返回错误代码
【发布时间】:2022-10-15 04:59:44
【问题描述】:

git clang-format 是一个方便的工具,可以仅在 git 补丁触及的行上运行 clang-format。我想阻止自己不小心提交和推送我忘记运行 git-clang-format 的补丁。例如。通过向.git/hooks/pre-commit 添加一个检查,确保git clang-format HEAD~1 无事可做。但是,返回代码看起来并没有改变。

clang-format本身有--dry-run -Werror:Can 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

【问题讨论】:

    标签: git clang-format


    【解决方案1】:

    作为一种解决方法,我正在检查 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}'
    

    由于两者都使用管道,因此差异中的颜色被删除。为了在 .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
    

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 2020-01-18
      • 1970-01-01
      • 2014-09-10
      • 2014-10-26
      • 2015-08-06
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多