24

What is the easiest way to determine in which commit a particular file was added to the repo?

pants
  • 192
  • 13
AlexanderLedovsky
  • 727
  • 1
  • 6
  • 18

4 Answers4

33

It is easy. following command shows first commit that file was added to the repo.

git log --oneline filename | tail -1
ton
  • 1,524
  • 13
  • 10
10

If you really want to find the commit that introduced a file you must consider renames. Thus use

git log --follow --diff-filter=A -- <filepath>

--diff-filter=[(A|C|D|M|R|T|U|X|B)…​[*]]
Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R) ...

--follow
Continue listing the history of a file beyond renames (works only for a single file).

Eventually you also must adjust the --find-renames threshold.

--find-renames[=]
If generating diffs, detect and report renames for each commit. For following files across renames while traversing history, see --follow. If n is specified, it is a threshold on the similarity index (i.e. amount of addition/deletions compared to the file’s size). For example, -M90% means Git should consider a delete/add pair to be a rename if more than 90% of the file hasn’t changed. Without a % sign, the number is to be read as a fraction, with a decimal point before it. I.e., -M5 becomes 0.5, and is thus the same as -M50%. Similarly, -M05 is the same as -M5%. To limit detection to exact renames, use -M100%. The default similarity index is 50%.

René Link
  • 48,224
  • 13
  • 108
  • 140
3

You can say:

git log -1 --reverse --pretty=oneline filename

This should give you the first commit.

From git help:

   -<n>
       Limits the number of commits to show. Note that this is a commit
       limiting option, see below.

   --reverse
       Output the commits in reverse order. Cannot be combined with
       --walk-reflogs.

For eliminating the commit message, say:

git log -1 --format="%H" --reverse filename
devnull
  • 118,548
  • 33
  • 236
  • 227
  • 1
    While this is probably the best you can do for the "normal" case (file added and then repeatedly modified), I'm not sure there is one good solution if the file was e.g. added, modified, removed, then reintroduced at a later date, or if the file came into existence as a result of a sequence of renames, etc... – twalberg Oct 31 '13 at 13:55
  • 2
    ```Note that these are applied before commit ordering and formatting options, such as --reverse.``` Your limit for 1 commit will be applied _before_ reversing – Alexander Apr 30 '19 at 08:42
1

Probably the easiest thing is something simple:

git log FILE | grep commit | tail -1 | awk '{ print $NF }'
Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69