Wednesday, March 9, 2016

Git Merge at last

So finally, I learn git merge.

Let say we do:

git init
git add abc.py
git commit -m "Initial Commit"
Now here is the image

 
Now master is the name of the default branch. HEAD is always where you are at the moment. Origin is the default remote name (in case you have a github backup).
Now if we add some file or make change to abc.py and commit,
git add abc.py
git commit -m "Commit 2"
Then we will have the image

Both master and HEAD move to the new commit. Now let's say we have a bug in C2, and want to create a branch to fix this bug. We can do

git checkout -b bug1
git add abc.py # with attempted bug fixed
git commit -m "Trying to fix bug"

This will be the image

So master is at old place, HEAD is now pointing to new label "bug1", which points at new commit. Meanwhile, we can go back at master and make some update

git checkout master
git add abc.py
git commit -m "Add new feature. While the bug is still there"

Here is the mental image



Finally, we want to merge C4 and C3. We can do

git merge bug1

This will gives an error if there is conflict. It will automatically add to the abc.py file lines that look like
>>>>>>>>>
this line appear in C4
=========
but this line appears in C4
<<<<<<<<<

We will open that abc.py file, resolve the conflict by remove those code blocks. Then we can
git add abc.py
git commit -m "Successful merge"

Now the two branches will be merged. And the image is


A couple notes: when you do git checkout, you can checkout a commit name, e.g. C1, C2. This will result in a complain from git called headless. HEAD should often be pointed to a label, e.g. master or bug1.
Another note, if we try to merge two nodes, and on of them is the parent of the other, then it will just fastforward to the more current node without any conflict.
Final note, if you want to create a branch from old node/commit, you can do
git branch branchname <sha1-of-commit>

No comments:

Post a Comment