Read more

Git: How to get a useful diff when renaming files

Thomas Klemm
February 13, 2015Software engineer

tldr; Use git diff -M or git diff --find-renames when you've moved a few files around.

Usage

$ git diff --help
  Options:
    -M[<n>], --find-renames[=<n>]
      Detect renames. 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%.

An example:

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Before: The diff shows that one file has been removed and another one added.

$ git diff

diff --git a/app/models/content_migration/photo.rb b/app/models/content_migration/photo.rb
deleted file mode 100644
index fea2bca..0000000
--- a/app/models/content_migration/photo.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-class ContentMigration::Photo < ActiveRecord::Base
  # ...

# ...

diff --git a/app/models/content_migration/record/photo.rb b/app/models/content_migration/record/photo.rb
new file mode 100644
index 0000000..2c8b70a
--- /dev/null
+++ b/app/models/content_migration/record/photo.rb
@@ -0,0 +1,42 @@
+class ContentMigration::Record::Photo < ActiveRecord::Base
  # ...

After: The diff shows that a file has been renamed.

$ git diff -M

diff --git a/app/models/content_migration/photo.rb b/app/models/content_migration/record/photo.rb
similarity index 95%
rename from app/models/content_migration/photo.rb
rename to app/models/content_migration/record/photo.rb
index fea2bca..2c8b70a 100644
--- a/app/models/content_migration/photo.rb
+++ b/app/models/content_migration/record/photo.rb
@@ -1,4 +1,4 @@
-class ContentMigration::Photo < ActiveRecord::Base
+class ContentMigration::Record::Photo < ActiveRecord::Base
   # ...
Thomas Klemm
February 13, 2015Software engineer
Posted by Thomas Klemm to makandra dev (2015-02-13 15:32)