Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move commits to another branch?

I'd like to move my last few commits from master into a branch of their own.

The tree on my PC looks like that:

   W (some branch)
  /       
X1--X2--X3--X4--Y--Z1--Z2 (master)

I'd like it to look like:

   W (some branch)
  /       
X1--X2--X3--X4 (master)
             \
              Y--Z1--Z2 (my new branch)

However, the tree at GitHub looks like:

   W (some branch)
  /       
X1--X2--X3--X4--Y (master)

That's what I saw as a solution for moving the last commits to another branch:

git checkout master
git branch my_new_branch
git reset <commit_id>

My question is: would I be able to successfully push to GitHub after moving the commits into a new branch and if so would it require to do something else than these three commands?

like image 336
Albus Dumbledore Avatar asked May 17 '11 18:05

Albus Dumbledore


2 Answers

(I assume <commit_id> is the object name of X4...)

Those commands will indeed end you up with what you want locally. (You might want to use git reset --hard to keep the working tree and index the same as the commit you're resetting to, but as usual, be very careful that git status is clean before you use that command.)

If you afterwards try to push master to GitHub, it will tell you that everything's already up to date, because the master on GitHub is one commit ahead. You can force the push, so that master is reset on GitHub, but that's rewriting public history, so you should only do that if (a) you're the only who'll have fetched master from GitHub or (b) you can let your collaborators know what do so that they don't accidentally merge Y back in. If that's OK, you can do:

 git push --force origin master

... and then master on GitHub will be the same as your local version.

like image 193
Mark Longair Avatar answered Nov 09 '22 23:11

Mark Longair


It should work but you will need:

  • to push -f origin master (force the push, which will spell trouble if anyone else has already clone your repo)
  • to push then your new branch (which will then find the X4 sha1 on top of which said new branch will be set).
like image 31
VonC Avatar answered Nov 09 '22 23:11

VonC