Git: How to get a useful diff when renaming files

Posted . Visible to the public.

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:

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
   # ...
Last edit
Deleted user #3651
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2015-02-13 14:32)