tags:

views:

81

answers:

1
+1  Q: 

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:

--cached
    Instead of searching in the working tree files, check the blobs
    registered in the index file.

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

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.

+1  A: 
$ 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
Greg Bacon
Thanks. You've helped me understand my concept error (see update in the description). So what I'm really looking for is something combining git diff and grep. The pager works, but it's not what I'm looking for ;)
Jeffrey Harris
See updated response.
Greg Bacon
Sweet! That's exactly what I wanted!
Jeffrey Harris