How to fix committing to the wrong Git branch?

前端 未结 11 1425
小鲜肉
小鲜肉 2020-11-29 14:09

I just made a perfectly good commit to the wrong branch. How do I undo the last commit in my master branch and then take those same changes and get them into my upgrade bran

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 15:00

    For multiple commits on the wrong branch

    If for you, it is just about 1 commit, then there are plenty of other easier resetting solutions available. For me, I had about 10 commits that I'd accidentally created on master branch instead of, let's call it branch_xyz, and I did not want to lose the commit history.

    What you could do, and what saved me was using this answer as a reference, using a 4 step process, which is -

    1. Create a new temporary branch from master
    2. Merge into the branch originally intended for commits, i.e. branch_xyz
    3. Undo commits on master
    4. Delete the temporary branch.

    Here are the above steps in details -

    1. Create a new branch from the master (where I had accidentally committed a lot of changes)

      git checkout -b temp_branch_xyz
      

      Note: -b flag is used to create a new branch
      Just to verify if we got this right, I'd do a quick git branch to make sure we are on the temp_branch_xyz branch and a git log to check if we got the commits right.

    2. Merge the temporary branch into the branch originally intended for the commits, i.e. branch_xyz.
      First, switch to the original branch i.e. branch_xyz (You might need to git fetch if you haven't)

      git checkout branch_xyz
      

      Note: Not using -b flag
      Now, let's merge the temporary branch into the branch we have currently checkout out branch_xyz

      git merge temp_branch_xyz
      

      You might have to take care of some conflicts here, if there are. You can push (I would) or move on to the next steps, after successfully merging.

    3. Undo the accidental commits on master using this answer as reference, first switch to the master

      git checkout master
      

      then undo it all the way back to match the remote using the command below (or to particular commit, using appropriate command, if you want)

      git reset --hard origin/master
      

      Again, I'd do a git log before and after just to make sure that the intended changes took effect.

    4. Erasing the evidence, that is deleting the temporary branch. For this, first you need to checkout the branch that the temp was merged into, i.e. branch_xyz (If you stay on master and execute the command below, you might get a error: The branch 'temp_branch_xyz' is not fully merged), so let's

      git checkout branch_xyz
      

      and then delete the proof of this mishap

      git branch -d temp_branch_xyz
      

    There you go.

提交回复
热议问题