I have two working branches, master and forum and I've just made some modifications in forum branch, that I'd like to cherry-pick into master. But unfortunately, the commit I want to cherry-pick also contains some modifications that I don't want.
The solution would probably be to somehow delete the wrong commit and replace it with two separate commits, one with changes I want to pick in master, and others that doesn't belong there.
I've tried doing
git reset --hard HEAD^
which deleted all changes, so I had to go back with
git reset ORIG_HEAD
So my question is, what is the best way to split last commit into two separate commits?
Best Answer
You should use the index. After doing a mixed reset ("git reset HEAD^"), add the first set of changes into the index, then commit them. Then commit the rest.
You can use "git add" to put all changes made in a file to the index. If you don't want to stage every modification made in a file, only some of them, you can use "git add -p".
Let's see an example. Let's suppose I had a file called myfile, which contains the following text:
I modified it in my last commit so that now it looks like this:
Now I decide that I want to split it into two, and I want the insertion of the first line to be in the first commit, and the insertion of the last line to be in the second commit.
First I go back to HEAD's parent, but I want to keep the modifications in file system, so I use "git reset" without argument (which will do a so-called "mixed" reset):
Now I use "git add -p" to add the changes I want to commit to the index (=I stage them). "git add -p" is an interactive tool that asks you about what changes to the file should it add to the index.
Then I commit this first change:
Now I can commit all the other changes (namely the numeral "2" put in the last line):
Let's check the log to see what commits we have: