gitazuregit-commitgit-pushazure-repos

How can I roll back an outgoing commit that has not been pushed up to devops?


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.


Solution

  • 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.

    enter image description here

    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.