Git预先提交钩以检查虚假空间 [英] Git pre-commit hook to check spurious spaces

查看:126
本文介绍了Git预先提交钩以检查虚假空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个预先提交的钩子:


  • 如果我有虚假空间,则禁止提交




  • 这是我的实际代码

     #!/ bin / sh 

    #Vérifieravant un commit que l'on n'pas pas de de spurious spaces。
    a = $(git diff --check | wc -c)
    if [$ a -gt 0]
    then
    echoSpurious space
    exit 1
    else
    echook
    fi

    如果我手动运行在与虚假空间差异的脚本中,我获得了虚假空间。这是完美的。但是,如果我将它作为pre-commit钩子运行,我总是会获得ok。



    我的代码出了什么问题?

    ,而不是工作目录中的内容,而不是 code> HEAD 修订版。这很容易通过 git diff --cached 来完成(它可以与 - check >混合使用)。



    作为一个较小的改进, git diff --check (有或没有 - cached <
    $ b


    如果发现问题,则退出非零状态。


    (请参阅文档)。因此,如果您愿意让diff本身显示在屏幕上:

     #! / bin / sh 
    git diff --check --cached

    预先提交的钩子。如果您希望在没有空格错误的情况下运行其他测试:

     #! / bin / sh 
    git diff --check --cached ||退出$?
    ...在这里的附加测试...

    应该有效。


    I would like to make a pre-commit hook which:

    • forbide commit if I have spurious space
    • allow it in other way.

    That is my actually code

    #!/bin/sh
    #
    # Vérifier avant un commit que l'on n'a pas mis de spurious spaces.
    a=$(git diff --check | wc -c)
    if [ $a -gt 0 ]
    then
     echo "Spurious space"
     exit 1
    else
      echo "ok"
    fi
    

    If I run manually the script in a diff with spurious spaces, I obtain "Spurious space". That is perfect. But if I run it as a pre-commit hook, I always obtain "ok".

    What's wrong in my code?

    解决方案

    The most important thing here is that you need to compare what is to be committed, rather than what's in the working directory, against the HEAD revision. This is easily done with git diff --cached (which can be mixed with --check).

    As a smaller improvement, git diff --check (with or without --cached) already:

    Exits with non-zero status if problems are found.

    (see the documentation). Thus, if you're willing to let the diff itself show on the screen:

    #! /bin/sh
    git diff --check --cached
    

    should suffice as the entirety of the pre-commit hook. If you want to run additional tests if there are no white-space errors:

    #! /bin/sh
    git diff --check --cached || exit $?
    ... additional tests here ...
    

    should do the trick.

    这篇关于Git预先提交钩以检查虚假空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆