Jeffrey Harris Jeffrey Harris - 3 months ago 17
Git Question

git grep --cached

Am I misunderstanding how

git grep --cached foo
works? Running git version 1.6.4.4 or 1.6.5.2,
git grep --cached foo
returns exactly the same thing as
git grep foo
.

I thought it would work like
git diff --cached
, searching only changes in the staging area. That’s certainly what the man page leads me to believe:


git diff [--options] --cached [<commit>] [--] [<path>…]


This form is to view the changes you staged for the next commit relative to the named
<commit>
. Typically you would want comparison with the latest commit, so if you do not give
<commit>
, it defaults to
HEAD
. If
HEAD
does not exist (e.g., unborn branches) and
<commit>
is not given, it shows all staged changes.
--staged
is a synonym of
--cached
.


Is this just a bug, or is there an alternate/better way to find changes about to be committed that mention foo?

git diff --cached | grep foo


The command above gives me half of what I want, but it loses the context of which file the change appears in.

UPDATE

It appears I have a concept error for what
--cached
is looking at. It looks like it’s searching the state of the tree assuming the staging area is applied. That makes sense, now that I think about it. What I want to search in is the difference, not the full tree.

Specifically, I want to know the list of all files (I don’t care about line numbers or context) that I’m about to commit
SpecialLog(...)
into, so I can go edit those files and remove
SpecialLog
. So yes, I can just do
git diff --cached
and search in the pager for
SpecialLog
, but then for huge changes in a single file, there are a lot of duplicates and it’s not obvious which file I’m looking at.

Answer
$ git init
Initialized empty Git repository in /tmp/foo/.git/
$ echo hi there >file
$ git add file
$ git commit -m 'added file'
[master (root-commit) dc08993] added file
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 file
$ echo hi again >>file
$ git grep again
file:hi again
$ git grep --cached again
$

Time passes...

$ git add file
$ git grep --cached again
file:hi again

To limit the scope of your search to the contents of the next commit, git diff pipes its output to $PAGER. Assuming you've set your pager to less, git diff --cached shows search matches in context.

Search the index for files with changes that mention a special string as in the following example:

$ echo SpecialLog >file2
$ git add file2
$ git diff-index --cached --name-only HEAD
file
file2
$ git diff-index --cached -SSpecialLog --name-only HEAD
file2
$ git diff --cached -SSpecialLog --name-only
file2