Search code examples
gitgit-history-graph

In Git how to fix a delete then re-add commit that's way back in the history?


In a project a subcontractor moved some files around in the tree, did a commit (Git marked them as deleted), used git add to re-add them to the tree. That happened several commits ago. Before I merge the changes back into my tree, I'd like to fix this. How can I "reconnect" these files at the right place in the git history?

Update

Okay, so, because people are suggesting a commit undo. That's not what I want (I think).

Imagine the following situation

A
|
|\
| \
|  B
|   mv file_x file_y
|   git commit 1
|   |
|   |
|   git commit 2
|   |
|   |
|   git commit 3
|   |
|   |
|   git add file_y
|   git commit 4
| /
|/
|

I'd like to "splice" the history of file_x up to commit 1 with file_y since commit 4 without loosing any of the other changes that happened in between and commits 1 and 4.


Solution

  • One possibility would be to create a second branch, reset the first branch to prior to the offending commit, then cherry-pick the desirable commits from the second branch.

    git checkout branch1
    git checkout -b branch2
    git reset --hard <commit sha>
    git cherry-pick <commit sha from branch 2>
    ...