I’ve created a branch and made some changes and attempted to commit and push. The commit was created, but the push failed because I hadn’t selected the branch I should have been developing on and was trying to push to the main branch (which is disabled here).
Is there a way, I can rollback the commit to bring git back to the state it was before commiting, i.e. I have outstanding items locally and no unpushed commit? At that point, I can stash, change branches and then apply the changes to the right branch.
Edit: This is different to the question identified below because the commit hasn’t successfully been pushed up to the devops server. It is a specific case.
2
Answers
Yes, you can roll back the commit to get back to the state before committing. Here’s how you can do it:
1.Use the
git reset
command to undo the commit but keep your changes in the working directory.git reset HEAD~
This command will reset your branch to the state it was before the last commit, but your changes will remain in your working directory.
2.Now that your changes are back in the working directory, you can stash them.
git stash
3.Change to the branch you intended to work on.
git checkout your-target-branch
4.Finally, apply the stashed changes to the correct branch.
git stash pop
This way, you’ll have your changes on the correct branch, ready to be committed and pushed.
Your current state is
where
C
is your most recent commit that diverged fromorigin/master
. You want a feature branch with the change set fromC
,that you can then push to
origin/feature
.We start with creating the
feature
branch off of the currentmaster
withwhich leads us to
Now we reset
master
to its previous state:Push the feature branch as usual:
and we end with the desired branch layout: