David Alsh
David Alsh

Reputation: 7675

How to undo commit, put into new branch then do a PR?

I have a master branch that is protected with push only by PR.

Say I thoughtlessly on master:

git add .
git commit -m "bunch of changes"

But I push to the branch and am rejected because the branch is protected. How do I backtrack, preserve my changes, and do a PR?

Upvotes: 6

Views: 2067

Answers (2)

Sajib Khan
Sajib Khan

Reputation: 24194

  1. Undo the last commit of master branch.

    $ git reset --soft HEAD~1      # undo the last commit and keep the changes in working tree   
    
  2. Checkout to new branch (say, feature), then Add, Commit and Push to remote feature branch.

    $ git checkout -b feature      # create and checkout to new 'feature' branch
    $ git add -A                   # add the changes 
    $ git commit -m 'message'      # commit 
    $ git push origin HEAD         # push to remote 'feature' branch
    

Now, Create a PR from feature branch.


Alternate:

  1. Checkout to new branch (say, feature) and push the feature branch to remote.

    $ git checkout -b feature
    $ git push origin HEAD
    
  2. Switch to master branch and undo the last commit.

    $ git checkout master
    $ git reset --hard HEAD~1
    
    Or, (reset the local 'master' with 'origin/master')
    $ git checkout master 
    $ git fetch origin
    $ git reset --hard origin/master
    

Now, Create a PR from feature branch.

Upvotes: 7

arc4randall
arc4randall

Reputation: 3293

git reset HEAD~
git checkout -b "name-of-new-branch"
git -am "my fancy new commit"
git push origin "name-of-new-branch"

reset HEAD~ will undo your last commit. Checkout -b makes creates a new branch and checks it out, then you just add and commit your changes there and push

Upvotes: 1

Related Questions