How grep through your staged files prior to committing?

后端 未结 3 843
灰色年华
灰色年华 2021-02-19 22:05

So prior to running git commit I often will run the following:

git grep --cached -l -I \"debugger\"

I thought it was similar to:

3条回答
  •  日久生厌
    2021-02-19 22:42

    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 :
    

    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.

提交回复
热议问题