How Git merge works

Git merge will make a bit more sense if we look at an example. Let’s assume Jack has created a new, empty repository containing only a text file. He edits the file to include, “You people,” and saves it with a cmt 1 change. After realising he had forgotten some important details, Jack adds “Season one” as the cmt 2 to the file.

The file content and commit tree look like this.

1
2
You people
Season one
gitGraph commit id: "cmt1" commit id: "cmt2"

Jack then decides to create a branch in order to add more text to YouPeople.md. Let us refer to the branch as feature/further-text. She adds “Episode one.” to the YouPeople.md file and saves the change as cmt3.

On feature branch, the content of the file looks like that

1
2
3
You people
Season one
Episode one
gitGraph commit id: "cmt1" commit id: "cmt2" branch feature/further-text commit id: "cmt3"

Along the way, Alice, another developer, decides that “Season one” should be changed to “Season 1.” This change is committed to main as cmt4.

On main branch the content of file is:

1
2
You people
Season 1

Now the commit tree looks like below:

gitGraph commit id: "cmt1" commit id: "cmt2" branch feature/further-text commit id: "cmt3" checkout main commit id: "cmt4"

To include the changes made to main into his feature branch, Jack may merge main into feature/further-text. Since the most recent commit on main (cmt4) is not a predecessor to the most recent commits on the branch feature/further-text (cmt3), it follows that new commits have been made on main since the feature branch was initially created.

When merging new commits to main and the feature branch, Git performs a three-way merge between the branch tips (cmt4 for main and cmt3 for feature/more-sentences) and their last common ancestor (cmt2). A new commit with cmt3 and cmt4 as its parents is created by the three-way merge.

gitGraph commit id: "cmt1" commit id: "cmt2" branch feature/further-text commit id: "cmt3" checkout main commit id: "cmt4" merge feature/further-text id: "merge commit"

The final content of the text file after merge should be like that

1
2
3
You people
Season 1
Episode one
updatedupdated2024-01-172024-01-17