With every software development project, there comes a time when a developer will refactor the code and move the files managed by the DVCS tool. Whenever these housekeeping tasks are performed, always complete the file moves and renames within a single commit and keep that commit free of code changes. The file move or the file renaming shouldn’t coincide with any other task.
Let’s examine why a developer should always move and rename Git files in an isolated commit.
Move and rename Git files carefully
There are two key reasons to follow this Git best practice. The first is that Git doesn’t always handle a file move or renaming seamlessly, especially if the task is done at the filesystem level and not with the Git mv command. For example, if a file is moved but the new location isn’t added to the index, Git assumes the file was deleted.
It’s only after the file is added in the new location that Git can look at some of the file’s metadata to determine there was a move. If the moved file is added to the index after several commits have already occurred, Git will treat it as a new file, not a moved one.
Simplify code audits and troubleshooting
The second reason to isolate all file rename and move functions within a single Git commit is purely a human one. This step makes it much easier to understand what happened during a given set of local commits, or when a developer searches through a commit history on a cloud hosted tool like GitHub.
It can be quite disconcerting to search the commit history or inspect a piece of code only to discover that a file or two has been completely removed from the Git working tree. And it can be especially problematic if the change wasn’t effectively tracked by Git. If a developer couples a file rename or move placed within a single commit with a well thought out commit message, it will be much easier to troubleshoot code and inspect a fellow developer’s work.
It’s not tough to do. If you have to move or rename a Git file in a repository, perform that function in a single, isolated commit. The rest of the development team will thank you for it.