gitgit-restore

After a force push, how do I reset the branch to a commit that others (merged this branch) can use and keep my current changes?


I have a PR which I did some force pushes on. I found out that someone else merged my branch and used it in theirs. I would like to

  1. Reset my branch to the commit that they merged in
  2. Add the changes introduced after that commit

That way they don’t have to change their branch if my branch gets merged first.

I just want to commit all my new changes in one commit. There’s enough divergence at this point that using rebase or cherry-picking would be too fiddly.


Solution

  • First find the commit that they merged. Maybe search the git log of their branch and look for Merged in… <branch>.

    Now take that merge commit and do git log -1 <merge>^2. That gives you the commit you are after. Let’s call it <merged>.

    Then find the commit that you are currently on and remember that. Let’s call the hash <current-tip>.

    Now do git reset --hard <merged>. Then do git restore -s <current-tip> .. Now stage those changes and commit.

    You can check out that other branch and do a test merge in order to make sure you did it correctly:

    git checkout --detach <other-branch>
    git merge <your-branch>
    

    You might get merge conflicts but as long as it is mergeable you’re good.