Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git grep--but restricted to new or modified files in the index

Tags:

git

grep

Is it possible to get git grep to search only new or modified files in the index/cache?

(The use-case for this is to use in a pre-commit hook that looks for "debug" code such as console.log in the prospective commit. But I'm not bothered by console.log in "existing" code. Preferably this would also fail to match instances of console.log that are removed, but I can live with those matching!)

like image 351
mjs Avatar asked Dec 19 '12 15:12

mjs


People also ask

What files are searchable by git grep?

`git grep` command is used to search in the checkout branch and local files. But if the user is searching the content in one branch, but the content is stored in another branch of the repository, then he/she will not get the searching output.

Which statement is the best comparison between git grep and grep?

The git grep version will only search in files tracked by git, whereas the grep version will search everything in the directory. So far so similar; either one could be better depending on what you want to achieve.

How does git know which files have changed?

Indexing. For every tracked file, Git records information such as its size, creation time and last modification time in a file known as the index. To determine whether a file has changed, Git compares its current stats with those cached in the index. If they match, then Git can skip reading the file again.

Why is git grep faster than grep?

That's because git-grep doesn't need to bother to go through the filesystem for the on-disk files. It greps directly from the object storage instead. And AFAIK it can run the grep in parallel.


1 Answers

It turns out the way to do this is not via git grep, but by a completely different command, that also happens to be able to search: git diff-index. (Another triumph for simplicity and orthogonality...)

What I wanted can be achieved via:

$ git diff-index -U --cached -G <regexp> HEAD
like image 113
mjs Avatar answered Oct 05 '22 04:10

mjs