Retrieve code changes after rejected git push

This is what happened:

  1. I started to implement a new feature in a protected branch from push (I forgot to check the branch)
  2. Once I was ready to push, I executed: git add + git commit -m "my message" and git push
  3. The changes were rejected because I was in a protected branch

But after that, my local git showed the changes as commited/pushed and when I execute git status, this is what I have:

On branch staging
nothing to commit, working tree clean

Is it possible to "undo" the procedure and move my code changes to a new branch, which will be merged to a protected branch via pull request later on?

Upvotes: 1

Views: 546

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391604

To move your commits to a new branch, you can do the following:

  1. Make sure you do not have any uncommitted changes before doing this, one of the steps below will do a hard reset, which will wipe out such changes

    If in doubt, make a backup of your entire working folder, with the .git repository inside, to make sure you don't mess anything up

  2. Make sure you have the feature branch that is protected checked out locally, at your latest commit, the one you didn't manage to push

  3. Create a new branch:

    git branch new-feature-branch
    

    (note, this does not check out the new branch, so you're still on the previous feature branch, the one that is protected)

  4. Reset the feature branch back to where the remote says it is

    assuming your remote is origin:

    git reset --hard origin/feature-branch-name
    
  5. Check out and push your new branch

    git checkout new-feature-branch
    git push --set-upstream origin new-feature-branch
    
  6. Go through the pull request process in gitlab or github

Upvotes: 2

Related Questions