Search code examples
gitrebaserecoverymerge-conflict-resolutionrevision-history

git rebase merge conflict mistake, selected deleted instead of created file


During a git rebase origin/main I ran into a merge conflict. A file did not exists in the local branch but in the main branch. I then ran git mergetool and it asked me what I want to do:

Merging:
src/CMakeLists.txt

Deleted merge conflict for 'src/CMakeLists.txt':
  {local}: created file
  {remote}: deleted
Use (c)reated or (d)eleted file, or (a)bort? d

I selected (d)eleted file, which was wrong. After I continued the rebase I found that the file was missing.

I then checkout out the missing file using git checkout origin/main src/CMakeLists.txt, so I could recover the file. However, the commit history now has an unintended additional commit which may lead to problems if further rebases may be necessary. I would merely like to undo my decision so that the commit history would be the same as if I had selected the correct answer in the first place.


Solution

  • If it is just about keeping the origin/master version of CMakeLists.txt through all your history :

    • run git rebase -i origin/master
    • in the list of actions, add a break instruction right after the first commit, save & exit
    • when git rebase stops, run
      git checkout origin/main -- src/CMakeLists.txt
      git commit --amend
      
    • run git rebase --continue
    • if you have conflicts on that file, you know can always run git checkout origin/master -- src/CMakeLists.txt to restore that version
    • you may have git rebase stopping because there are no changes left for a particular commit, in that case run git rebase --skip to skip replaying that commit

    If, on the other hand, you had modifications on that file which you want to preserve and restore :

    • inspect your reflog : git reflog or git reflog my/working/branch
    • spot the state of your branch before you ran git rebase
    • return to that point : git reset --hard <sha>
    • run git rebase origin/master again

    A generic warning on git reset --hard :
    run it on a clean worktree, it is one of the very few commands in git that can remove some files or modifications from your disk without them being stored in git.