Use git-mv to Rename or Move a File
git mv [source_file] [destination_file]
to rename or move a file instead of renaming or moving a file directly (e.g. from IDE, or via
mv). This is helpful for preserving history and potentially helpful for preventing merge mistakes.
According to Git - git-mv Documentation,
git-mv - Move or rename a file, a directory, or a symlink.
Sure, renaming or moving a file can be done simply via
mv command or a few clicks in a IDE/Editor, but there are a few downsides and potential risks.
For example, we have a repo with only one file
test.txt, there are two commits in log.
If we move the file using
mv command, and make some change in the new file,
git status would show the old file was deleted, new file was created. It looks perfectly normal, doesn’t it?
Not quite, if we check the diff, e.g.
git diff, you would only see new file was created, old file was deleted, there is no liason between the two, it’s not easy to find the actual code change, bug could be introduced without much attention.
Besides, between the commit #2 and #3, if someone just submitted a change on the old file, before you submit #3 you would need
git rebase or
git merge, then submit your commit as #4. But wait, how do you replicate the change on the old file to the new file you just created? Manual copy-paste with human-eye-checking? What if it’s a big change?
With this, git will help you to track the connection between the old and the new files.
Right now, the change is clearly presented in the diff.
If someone submitted the commit before you submit the new file, after the rebasing or merging, you should be able to see everything clearly, what file was deleted, what change was made by your teammate on the old file, what you just added in the new file, etc.
git mv to rename or move a file, it helps to preserve the full history and prevent potential merge mistakes.
By the way, right now Git is smart enough to find the liason between the old and new files, even if it’s done via
mv or from a IDE/Editor, it checks if the two files are sharing the majority parts or not.
However, it’s always safer by using