gitgithubgitlab

Strategies for spotting changes inside moved or renamed files in git


You know that scenario, it happened to you a thousand times :

  1. You have moved and renamed a file.
  2. Then you have modified it.
  3. After committing, you to need to cross fingers for git to detect that it's actually the same file (that part usually goes well)
  4. You create a PR for a series of commits containing that moving/renaming
  5. You want to review the changes (by using tools such as gitlab or others). Problem: the two versions of the file (the deleted one and the new one containing the modifications) will still appear separately (despite having a nice little label warning you that the file got moved) and the modifications will still be hard to spot because the entire file appears as new (it's all green).

What are ways of mitigating this? The only solution I found so far is self-discipline: Enforce commits containing ONLY the file moving and renaming. Zero modification allowed. Leave that for a subsequent commit. Even better : Do the move/rename in an entirely separate PR (so that the actual changes are still easily visible in the "all changes" view of gitlab or other tools)

The difficulty with that approach is that it adds some overhead. Another problem is reluctant devs who don't want to comply to that or forget to do it, because they can't see that it was much easier for them to see the changes in a moved file at the time they committed than for the reviewer reading the final result.

Do you know of any other way?


Solution

  • yes you are right its either being deciplined or working with built in UI in your editor but if you find your self in a such situation then i hope this helps :

    1. Configure Git to better detect moves and copies

    git config --global diff.renames true

    git config --global diff.renameLimit 999999

    1. For reviewing changes in moved files:

    Show the diff of a moved file, ignoring the move itself

    git diff --color-moved=blocks --find-renames

    1. Alternative: Use git log with -M and -C options

    git log -M -C --stat --follow path/to/file

    1. For reviewing specific commits with moved files:

    git show --color-moved=blocks commit_hash

    1. To see the actual content changes in a moved file:

    git diff --color-moved=blocks HEAD^..HEAD path/to/new/file

    1. For more detailed move detection:

    git diff --find-renames=90% --break-rewrites

    1. To generate a patch that preserves move information:

    git format-patch --find-renames --break-rewrites HEAD^

    1. For branch comparison with move detection:

    git diff branch1...branch2 --color-moved=blocks --find-renames