Last Updated: February 25, 2016
· kaserf

Renaming and changing files in git without losing history

If you ever plan to do a major renaming of your code in a medium to large sized project, be kind and think about the size of your repo and your history. If you are renaming a file and change a substantial amount of the file, git will not recognize it as a renaming but will treat it as a delete-file / create-file case. This basically destroys all the history on that file, since the person doing the rename will check in a new file.

Linus Torvalds talks about this in a lengthy email, be advised is it Torvalds speaking, he can be rough:

So my advise: plan ahead! If you do this right you can save your history and keep the size of your repo low. You can apply a workaround to trick git into thinking you only renamed the files and did not delete and recreate them. First just do a renaming and check it in, you will have to commit it, just staging won't be enough. After that you can do all your changes to the files (e.g. change class and package names to fit the new structure. This will break your build for one commit, but you will have to deal with it.

If you already changed all at once: renaming the files and doing all the changes, there is still a way to do this: stash all your changes, do the renaming manually once again and check it in. After that you can get your changes from the stash and git should be smart enough to detect that it's just changes on the files (which keeps the history intact) and not a new file.

1 Response
Add your response

Great tip about stashing the changes and then doing a renaming. I'll have to try that next time.

over 1 year ago ·