Display only relevant hunks of a diff/patch based on a regexp

diff()gitpatch

git log -G<regex> -p is a wonderful tool to search a codebase's history for changes that match the specified pattern. However, it can be overwhelming to locate the relevant hunk in the diff/patch output in a sea of mostly irrelevant hunks.

It’s of course possible to search the output of git log for the original string/regex, but that does little to reduce the visual noise and distraction of many unrelated changes.

Reading up on git log, I see there's the --pickaxe-all, which is the exact opposite of what I want: it broadens the output (to the entire changeset), whereas I want to limit it (to the specific hunk).

Essentially, I’m looking for a way to "intelligently" parse the diff/patch into individual hunks and then execute a search against each hunk (targeting just the changed lines), discard the hunks that don’t match, and output the ones that do.

Does a tool such as I describe exist? Is there a better approach to get the matched/affected hunks?

Some initial research I've done…

  • If it were possible to grep the diff/patch output and make the context option values dynamic—say, via regexps instead of line counts—that might suffice. But grep isn't exactly built that way (nor am I necessarily requesting that feature).

  • I found the patchutils suite, which initially sounded like it might suit my needs. But after reading its man pages, the tools doesn't appear to handle matching hunks based on regexps. (They can accept a list of hunks, though…)

  • I finally came across splitpatch.rb, which seems to handle the parsing of the patch well, but it would need to be significantly augmented to handle reading patches via stdin, matching desired hunks, and then outputting the hunks.

Best Answer

here https://stackoverflow.com/a/35434714/5305907 is described a way to do what you are looking for. effectively:

git diff -U1 | grepdiff 'console' --output-matching=hunk

It shows only the hunks that match with the given string "console".