How grep through your staged files prior to committing?

你说的曾经没有我的故事 提交于 2019-12-04 01:29:14

If you have a Unix-like shell available, the answer is pretty simple:

git grep --cached "debugger" $(git diff --cached --name-only)

This will run git grep on the list of staged files.

A lot of pre-commit hooks use git diff-index --cached -S<pat> REV to find changes which add or remove a particular pattern. So in your case, git diff-index --cached -Sdebugger HEAD. You may want to add -u to get a diff as well, otherwise it just identifies the offending file.

First you need to get a list of files from the index (excluding deleted files). This can be done with the following:

git diff --cached --name-only --diff-filter=d HEAD

Second you need to use the : prefix to access the contents of a file in the current index (staged but not yet committed) see gitrevisions manual for more information.

git show :<file>

Finally here's an example of putting it all together to grep this list of files

# Get a list of files in the index excluding deleted files
file_list=$(git diff --cached --name-only --diff-filter=d HEAD)

# for each file we found grep it's contents for 'some pattern'
for file in ${file_list}; do
    git show :"${file}" | grep 'some pattern'
done

Also here's an example of a git pre-commit hook that uses this method to check that the copyright years are up to date in files to be committed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!