Git how to find all commits where string was mentioned

You can use the following Git commands to find commits where a string was added/modified/deleted. This can be helpful to find commits where a certain method was added, modified, deleted or usages were added/deleted.

1. Find commits where method was mentioned.

Powershell script (for Windows)

 # Replace 'YourMethodName' with the string you want to search for
$searchString = 'YourMethodName'

# Get the list of commits where the string appears in diffs
$commits = git log -G $searchString --pretty=format:"%H"

# Loop through each commit and show the diff with the specific lines
foreach ($commit in $commits) {
    # Get the commit details (date, author, message)
    $commitDetails = git show $commit --pretty=format:"Commit: %H`nAuthor: %an`nDate: %ad`nMessage: %s`n" --no-patch

    # Display the separator header
    Write-Host "-----" -ForegroundColor Yellow
    Write-Host 

    # Display the commit details with colors
    $details = $commitDetails -split "`n"
    Write-Host $details[0]
    Write-Host $details[1]
    Write-Host $details[2]
    Write-Host $details[3]
    Write-Host

    # Get the diff for the commit
    $diff = git show $commit --pretty="" --no-prefix

    # Split the diff into lines
    $diffLines = $diff -split "`n"

    # Initialize variables
    $currentFile = ""
    $relevantLines = @{}

    # Process each line in the diff
    foreach ($line in $diffLines) {
        if ($line -match '^diff --git a\/(.+?) b\/\1$') {
            # Extract the filename from the diff line
            $currentFile = $matches[1]
        } elseif ($line -match "(\+|\-).*${searchString}") {
            # Add the line to the relevant lines for the current file
            if (-not $relevantLines.ContainsKey($currentFile)) {
                $relevantLines[$currentFile] = @()
            }
            $relevantLines[$currentFile] += $line
        }
    }

    # Display the relevant lines grouped by filename
    foreach ($file in $relevantLines.Keys) {
        Write-Host "File: $file" -ForegroundColor Yellow
        foreach ($line in $relevantLines[$file]) {
            if ($line -match '^\+.*') {
                Write-Host $line -ForegroundColor Green
            } elseif ($line -match '^\-.*') {
                Write-Host $line -ForegroundColor Red
            } else {
                Write-Host $line
            }
        }
        Write-Host
    }
} 

Published
Categorized as Git

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *