Search code examples
gitgit-blame

Find first existence of a line of code in Git


I am trying to trace a piece of code (just a single line) to it's commit.

Using blame only points me to a commit where this line in question was moved as a part of an extract method style refactoring.

What techniques can I use to get to the commit were that particular text existed in the codebase for the first time?


Solution

  • As noted in this answer to git: finding a commit that introduced a string, you can simply use

    git log -S <line>
    # or
    git log -G <regex>
    

    to find the first occurrence of a line of code in a repository.

    From the official Linux kernel Git documentation for log:

    -S<string>
    

    Look for differences that introduce or remove an instance of <string>. Note that this is different than the string simply appearing in diff output; see the pickaxe entry in gitdiffcore(7) for more details.

    -G<regex>
    

    Look for differences whose added or removed line matches the given <regex>.