12

I made a number of changes that could break the code. I thought I was in a branch but was in master when I committed. Is there any way to move the 4 local commits to a branch locally and then push?

Sri9911
  • 1,187
  • 16
  • 32
Dov
  • 8,000
  • 8
  • 46
  • 75

3 Answers3

16

Going by the details you said (4 commits), you could do this:

git branch new-branch-name-here
# new commits on branch
git checkout master
git reset HEAD~4
# move HEAD (master) 4 commits back, commits are no longer on master
# note: that's a ~ (tilde, above your Tab), not a - (dash).
git push origin new-branch-name-here
# push new branch with correct commits to remote (assumed origin)
git push -f origin master
# if you already pushed master before, clear commits from remote
# otherwise, this can be skipped if master wasn't yet pushed remotely

The -f for pushing master is required, otherwise your push will get rejected by the server.

In general, changing commits on a branch in Git can be done in three easy steps:

  1. create new branch with your commits on it
  2. "re-wind" other branch so the commits are not on it
  3. push branches to remote (if necessary, using -f)
Teknikal_Domain
  • 318
  • 1
  • 11
8

You may also try

git reset HEAD~

This will revert the local commit and restore the changes. And then create a new branch, commit and push your changes over there.

Kurt
  • 1,169
  • 1
  • 9
  • 16
Sri9911
  • 1,187
  • 16
  • 32
  • 1
    This worked for me as I just needed a fresh start on the repo (and I'm not using rebase). Although I needed to add --hard. Simplicity FTW. – Erez Cohen Feb 05 '19 at 11:44
3

You should be able to just create your new branch, and then reset master back to the correct commit.

git branch oopsies-feature-branch
git branch -f master THE_RIGHT_COMMIT_FOR_MASTER
CollinD
  • 7,304
  • 2
  • 22
  • 45