如何仅对暂存内容运行git pre-commit检查? [英] How can I run git pre-commit checks only on staged content?

查看:270
本文介绍了如何仅对暂存内容运行git pre-commit检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设git status给出了这个信息:

# On branch X
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   file1.cc
#   modified:   file1.h
#   modified:   file1_test.cc
#   modified:   SConscript
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   (commit or discard the untracked or modified content in submodules)
#
#   modified:   file1.cc
#   modified:   tinyxml2 (untracked content)
#

在这种情况下,只有对file1.cc所做的某些更改已被暂存/为下一次提交编制了索引.

In this case, only some of the changes made to file1.cc have been staged/indexed for the next commit.

我运行预提交脚本来运行样式检查器:

I run a pre-commit script to do run a style checker:

#!/bin/bash                                                                                                                                                                     

git stash -q --keep-index

# Do the checks                                                                                                                                                                 
RESULT=0
while read status file
do
    if python ~/python/cpplint.py "$file"; then
        let RESULT=1
    fi
done < <(git diff --cached --name-status --diff-filter=ACM | grep -P  '\.((cc)|(h)|(cpp)|(c))$' )

git stash pop -q

[ $RESULT -ne 0 ] && exit 1
exit 0

根据此处的建议,在运行样式检查之前,我先存放了未暂存的文件,然后将其弹出.但是,在仅暂存文件中的某些更改的情况下,当我在预提交钩子的末尾弹出存储时,这会导致合并冲突.

As suggested by here, I stash unstaged files before I run my style checks, and pop them afterwards. However, in the case where only some of the changes in a file were staged, this causes a merge conflict when I pop the stash at the end of the pre-commit hook.

什么是更好的方法?我想对即将提交的文件的暂存版本进行样式检查.

What is a better way to do this? I want to run a style check against the staged version of the files about to be committed.

推荐答案

我会避免在挂钩中自动使用git stash.我发现可以使用git show ':filename'获取隐藏文件的内容.
相反,我使用了下一种方法:

I'd avoid using git stash automatically in hooks. I found that it is possible to use git show ':filename' to get contents of stashed file.
Instead I used next approach:

git diff --cached --name-only --diff-filter=ACMR | while read filename; do
    git show ":$filename" | GIT_VERIFY_FILENAME="$filename" verify_copyright \
        || exit $?
done \
    || exit $?

这篇关于如何仅对暂存内容运行git pre-commit检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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