Schwern
Schwern

Reputation: 165318

Can Git rename matching ignore whitespace changes?

When I rename a file and do whitespace changes (such as changing the indentation), Git cannot recognize the rename. And I can't find any combination of git diff flags to get it to ignore whitespace while looking for renames. This makes reviewing otherwise simple refactorings difficult.

For example...

$ git init
$ ruby -e '100.times { puts "Basset hounds got long ears" }' > file
$ git add file
$ git commit -m 'first commit'
$ git mv file file2

Everything is fine at this point.

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    renamed:    file -> file2

Now if I indent the lines in the file Git no longer recognizes the rename.

$ ruby -i -pe 'gsub(/^/, "  ")' file2
$ git add .
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    file
    new file:   file2

After I commit git diff -w HEAD^ still shows a delete and a new file. I can't find any git diff options which will recognize the rename.

Is there a set of options which allow Git to ignore whitespace when detecting copies and renames?

Upvotes: 7

Views: 490

Answers (1)

Fake Code Monkey Rashid
Fake Code Monkey Rashid

Reputation: 14577

Git cannot do this by default.

However, if you have the know-how, you can make it do so by changing the similarity index computation. The relevant code can be found here in diffcore-delta.c (which is well documented) and here in diffcore-rename.c.

Be aware that there are some starting checks and balances involved before Git even checks to see if a file can be considered as renamed (internally). This check will pass with a "yes" answer to the following question:

Is it a regular non-zero sized file that has not significantly changed in file size?

One approach therefore is to add your conditional check before that point so that if there are only differences in whitespace then the similarity index computes to 100% otherwise Git should do what it normally does.

That said, what you experienced is why it often recommended that you rename the file first before changing its contents but names aren't that easy to get right the first time.

Upvotes: 1

Related Questions