aknuds1
aknuds1

Reputation: 67997

How can I find modified lines that match a certain pattern with Git?

I wish to write a pre-commit Git trigger that finds unwanted changes. How can I find modified lines about to be committed by Git that match a certain pattern, while obtaining corresponding file name and line number?

Upvotes: 1

Views: 329

Answers (1)

VonC
VonC

Reputation: 1324847

Following the "Fun with git grep" article from Junio C Hamano (main maintainer of Git), you can use git grep:

git grep --cached -n -e 'What You are looking for' -- '*.typeOfFile'
git grep --cached -n -e "What You are looking for" -- '*.typeOfFile'

For instance:

C:\Users\VonC\prog\go\src\github.com\VonC\asciidocgo>
git grep --cached -n -e "testa" -- "*.go"
abstractNode.go:3:testa
^^^^^^^^^^^^^^^ |
  (file name)   --> (line number)

Note: for existing commits, you could have combined git grep (explained here) and git blame functions, as shown in this blog post

ggb.sh

# runs git grep on a pattern, and then uses git blame to who did it
ggb() {
    git grep -n $1 | while IFS=: read i j k; do git blame -L $j,$j $i | cat; done
}

But in your case, you want to look at the index (about to be committed), not existing commits.


Note that "git grep" did not quote a path with unusual character like other commands (like "git diff", "git status") do, but did quote when run from a subdirectory, both of which has been corrected with Git 2.27 (Q2 2020), .

See commit 45115d8 (19 Apr 2020) by Matheus Tavares (matheustavares).
(Merged by Junio C Hamano -- gitster -- in commit 33a1060, 28 Apr 2020)

grep: follow conventions for printing paths w/ unusual chars

Reported-by: Greg Hurrell
Helped-by: Johannes Schindelin
Signed-off-by: Matheus Tavares

grep does not follow the conventions used by other Git commands when printing paths that contain unusual characters (as double-quotes or newlines).
Commands such as ls-files, commit, status and diff will:

  • Quote and escape unusual pathnames, by default.
  • Print names verbatim and unquoted when "-z" is used.

But grep never quotes/escapes absolute paths with unusual chars and always quotes/escapes relative ones, even with "-z".
Besides being inconsistent in its own output, the deviation from other Git commands can be confusing.

So let's make it follow the two rules above and add some tests for this new behavior. Note that, making grep quote/escape all unusual paths by default, also make it fully compliant with the core.quotePath configuration, which is currently ignored for absolute paths.

Upvotes: 2

Related Questions