Search code examples
gitversion-control

Git - reset a branch that has been merged to another into previous commit


In my git project, I follow the following flow:

I am working on a branch named mybranch, push commits and when I want to make 'a version', I merge mybranch into 'develop' branch, then switch back to mybranch and repeat the same process.

Accidentally after a merge from mybranch to develop, I forgot to switch branches and stayed to 'develop' branch and pushed some commits straight to it (let's call them develop-commit-1, develop-commit-2, develop-commit-3).

Then 'mybranch' where I was working was behind 'develop' and I needed these commits (they were destined for this branch originally) so I thought that merging the develop branch back to the 'mybranch' will do the trick' (bad decision).

To my surprise, now I see the git history of 'develop' branch containing the commits of 'mybranch' and from the GUI I see the branches have been aligned (because of the vice versa merge git thinks they are the same or something?).

I want to return to my previous workflow (keep clean the develop branch and add only merges from mybranch into it), so I am thinking about resetting the 'develop' branch to the commit where last merged 'mybranch' into it, and then just merge 'mybranch' back to it as I used to do, will that work? I am really scared whether the reset of 'develop' branch back to that commit will affect 'mybranch' since they have been merged between them (and mybranch contains these 3 commits that are after the commit point where I want the develop branch to be reset, any advice here?

I can definitely give more information on that in case the description is not clear. Thanks in advance!


Solution

  • Branches are pointers to a single commit (a branch does not mean a collection of commits). Resetting a branch cannot have an effect on other branches.

    So you want to simply reset develop and keep your branch mybranch. Eventually, force-push your rewritten develop:

    git branch -f develop "$commit_before_your_accident"
    git push origin +develop:develop
    

    The 3 commits that were previously reachable through the develop pointer are no longer reachable through it, only through the mybranch pointer.

    But since your branch still contains the merge from develop and no new commits were made on develop, the next merge to develop is going to be a fast-forward. To force a real merge, you have to merge with the --no-ff flag.