git - Find commit where file was added

GitCommitGit CommitGit Log

Git Problem Overview


Say I have a file foo.js that was committed some time ago. I would like to simply find the commit where this file was first added.

After reading the answers and my own tinkering, this works for me

git log --follow --diff-filter=A --find-renames=40% foo.js

Git Solutions


Solution 1 - Git

Here's simpler, "pure Git" way to do it, with no pipeline needed:

git log --diff-filter=A -- foo.js

Check the documentation. You can do the same thing for Deleted, Modified, etc.

https://git-scm.com/docs/git-log#Documentation/git-log.txt---diff-filterACDMRTUXB82308203

I have a handy alias for this, because I always forget it:

git config --global alias.whatadded 'log --diff-filter=A'

This makes it as simple as:

git whatadded -- foo.js

The below one liner will recursively search through sub directories of the $PWD for foo.js without having to supply an absolute or relative path to the file, nor will the file need to be in the same directory as the $PWD

git log --diff-filter=A -- **foo.js

Solution 2 - Git

git log --follow --find-renames=40% --oneline -- foo.js | tail -n 1

Solution 3 - Git

The following may not be of your interest, but I think it will help you in the future and is part of the debugging ecosystem in Git:

You can use git-blame to show what revision and author last modified each line of a file, especially a file annotation. Visit https://git-scm.com/book/en/v2/Git-Tools-Debugging-with-Git

For example,

git blame -L 174,190  xx.py

The -L option is to restrict the output of the annotation to lines 174 through 190, so you will see the authors and the commit hash, etc from line 174 until 190 for the file xx.py

Solution 4 - Git

If it's an alternative to do it non-programatically, this is very quick. Open gitk GUI.

gitk file

Then just scroll to the first commit

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZomboView Question on Stackoverflow
Solution 1 - GitstelterdView Answer on Stackoverflow
Solution 2 - GitSeth RobertsonView Answer on Stackoverflow
Solution 3 - GitReidelView Answer on Stackoverflow
Solution 4 - GitMartin GView Answer on Stackoverflow