Getting Git to Acknowledge Previously Moved Files

Viewed 30244

I've moved a bunch of files around manually without thinking, and can't find a way to get git to recognize that the files are just moved and not actually different files. Is there a way to do this other than removing old and adding the new (and thus losing the history), or redoing all the changes with git-mv?

6 Answers

You can move/rename the new file back to its old name and path outside of git and then use git mv to stage just the move; for example in bash:

mv $NEW $OLD && git mv $OLD $NEW

Its somewhat cumbersome1, especially if you have to do it by hand. But it has the advandage that it leaves other changes such as changing the namespace or the class name unstaged so that you can inspect them and only stage them when you intent to do so.


1 I hope to find a better alternative and will update my answer when I find it.

Example: I moved a bunch of files fom oldDir to newDir and started enthusiastically with some other changes. Now I want to check what other modifications were made. Using and resulted in the following (on a single line):

git status --short |
gawk '/^\?\?/ && match($0, /newDir\/(*.\.cs)/, a) {print "newDir/" a[1] " " "oldDir/" a[1]}' |
xargs -n 2 bash -c 'mv $0 $1; git mv $1 $0'

Now git status shows the renames as "Changes to be committed" and the textual modifications under "Changes not staged for commit"

It happens to me, when I move and edit the file, it will no longer recognize it as moving file but a new one, so I lost history.

What I do it is to create 2 separated commits, one when I move the file, and then another editing the file. In this way I keep the history.

Related