Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking at git diff --name-status, how can I tell that a file has been renamed?

Tags:

git

I have a script that uses git diff --name-status to find the differences between a given branch and the master branch, and perform various actions depending on how each file changed.

Git does not track renames. While it knows that a file has been renamed when you stage the commit, git diff --name-status only shows that the old name has been deleted and the new name has been added. This is a problem for me, as I would like to take additional steps with my script for files that have been renamed.

Given the name of a file that has been added, how can I tell whether the file is entirely new or a rename of another file (and if it is a rename, what was its previous name)?

like image 729
zneak Avatar asked Mar 12 '23 17:03

zneak


1 Answers

Git does not track renames.

This is true! But ...

While it knows that a file has been renamed when you stage the commit,

... this, in fact, is not quite true: Git is simply guessing; git mv does not record the rename, and you can manually rename or copy the file, then just git rm --cached the old path and git add the new one (in either order), to the same effect.

git diff --name-status only shows that the old name has been deleted and the new name has been added.

You can get git diff to make the same guesses as git status by turning on rename detection. In fact, git status simply runs git diff with rename detection turned on, and some additional speeding-up options (e.g., telling git diff that it should not bother to attempt to produce a diff, just the --name-status info, which of course is also the case when you use --name-status).

To enable rename detection when running git diff:

  • add -M or --find-renames to the command line, or
  • set diff.renames to true (or even copies) in your configuration, or
  • upgrade to Git version 2.9 or later, where it defaults to enabled.

See also the descriptions of -M, -C, and -B in the git diff documentation, and the other configurable diff.* values in git config. (I keep diff.renameLimit set to 0, for instance.)

like image 104
torek Avatar answered Mar 15 '23 06:03

torek