skip to Main Content

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


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

    Login or Signup to reply.
  2. Your current state is

          C master
         /
    A---B origin/master
    

    where C is your most recent commit that diverged from origin/master. You want a feature branch with the change set from C,

          C feature
         /
    A---B master, origin/master
    

    that you can then push to origin/feature.

    We start with creating the feature branch off of the current master with

    git checkout -b feature master
    

    which leads us to

          C master, feature
         /
    A---B origin/master
    

    Now we reset master to its previous state:

    git checkout master
    git reset HEAD~
    

    Push the feature branch as usual:

    git push origin feature
    

    and we end with the desired branch layout:

          C feature, origin/feature
         /
    A---B master, origin/master
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search