You're going to need to use reset on your current branch - that's just how this works. Don't worry though - all your stuff will be safe by the time you use it.
First, while on your branch where you've accidentally added the commits (we'll call it branch1
) create a new branch (let's call it temp
)
git branch temp
As @bmargulies said, branches are just a reference to a commit. As long as you have a reference to a commit, you haven't lost it. We're going to move your branch1
branch back to where it started before you mistakenly made the commits, and so temp
is our reference to the commits you've added - think of it as a backup. We can now make all sorts of changes to where branch1
points without worrying about losing your new commits.
If A
, B
and C
were commits originally on branch1
and you accidentally added D
E
and F
then your commit history will now look something like the following (brackets show which commit each branch is referencing):
A <- B <- C <- D <- E <- F (temp)(branch1)
If you added, say, 3 extra commits (D
, E
and F
) that you didn't mean to add to branch1
, then you can reset branch1
back to where it should be using:
git reset --hard HEAD~3
Now things will look like this:
A <- B <- C (branch1)<- D <- E <- F (temp)
Now the scary part. Rebasing. Rebase has a flag --onto which takes the following form:
git rebase --onto <branch a> <branch b> <branch c>
What it basically says is "find the common ancestor of branch b
and branch c
, take the changes introduced by each commit between the common ancestor and branch c
and replay them onto branch a
.
The "common ancestor" stuff might sound scary, but if branch b
is an ancestor of branch c
(read: arrows point from branch c
to branch b
) then the commit branch b
points to is the common ancestor.
See where this is going? If we say the branch you want to move your commits onto is called branch2
then you can move the new commits to it using:
git rebase --onto branch2 branch1 temp
That will take commits D
, E
and F
and put them on the end of branch2
(they'll be called something else though as this is a rebase - you've said you haven't pushed to a public repo so this shouldn't be a problem)
branch1
will now be where it was before you mistakenly added those commits, the new commits will be sitting on the end of branch2
, and you can delete temp
using
git branch -D temp