Git: renamed file manually, Git confused

GitVersion Control

Git Problem Overview


I am using Git and manually renamed a file that I had added to the repository. Now, I have added the "new" file which I renamed to the repository but Git complains that the "old" file has been deleted. So how can I make Git forget about the old file? Better yet, how do I tell Git that the "new" file really is the "new" file so that I can keep the change history intact?

Git Solutions


Solution 1 - Git

There is no problem. Simply git rm old or even git add -A and it will realize that it is a rename. Git will see the delete plus the add with same content as a rename.

You don't need to undo, unstage, use git mv etc. git mv old new is only a short hand for mv old new; git rm old; git add new.

Solution 2 - Git

First, cancel your staged add for the manually moved file:

$ git reset path/to/newfile
$ mv path/to/newfile path/to/oldfile

Then, use Git to move the file:

$ git mv path/to/oldfile path/to/newfile

Of course, if you already committed the manual move, you may want to reset to the revision before the move instead, and then simply git mv from there.

Solution 3 - Git

Try this:

mv new old
git rm new
git mv old new

Solution 4 - Git

This has to be automated. I never remember git until I commit, and I don't want to.

#!/usr/bin/env python3

# This `git rm` wrapper respects the `--cached` option (like `git rm`).

import sys
import subprocess

if "--cached" in sys.argv:
    dest = sys.argv[-1]
    rest = sys.argv[1:-1]
    subprocess.check_call(["git", "add", dest])
    subprocess.check_call(["git", "rm"] + rest)
else:
    subprocess.check_call(["git", "mv"] + sys.argv[1:])

I don't want to "remember git mv", because git mv adds hidden state behind git diff that is implicitly added to the next commit, even if you explicitly commit something totally unrelated. I know, it's the so called "staged" state, but I don't like it. I like to commit without surprises.

Solution 5 - Git

If this error occurs, it probably means that the file you are trying to move is not originally tracked by git or the directory you are trying to move the file into is not a git tracked directory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmmerszView Question on Stackoverflow
Solution 1 - GitJakob BorgView Answer on Stackoverflow
Solution 2 - GitAmberView Answer on Stackoverflow
Solution 3 - GitChris HasińskiView Answer on Stackoverflow
Solution 4 - Gituser2394284View Answer on Stackoverflow
Solution 5 - GitCandida UstineView Answer on Stackoverflow