Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.4k points)

How does git compare two files? Which algorithms are used to compare two files? Does it compare line by line while merging?

I can't be sure whether the comparison of the two files produce conflict or not while merging.

1 Answer

0 votes
by (12.4k points)

There are several merge strategies.

3-way merge algorithm recurse is used in Git by default.

For example:

master: A -> B -> C

Create new branch

master: A -> B -> C

                   \

branch:             D

Some new commits

master: A -> B -> C -> E

                   \

branch:             D -> F

Here all changes made in 1.txt 

 commit C         commit E         commit F 

----------       ----------       ----------

  line a                            line a

  line b         new line d

  line c                          new line e

                   line a           line b

                   line b         new line f

                   line c           

                 new line g         line c

What happens if we merge two branches (commit E, commit F). Does it produce a merge conflict? No, Because git does not compare a file line by line rather It compares the context of the lines.

Align the 1.txt file

commit C         commit E         commit F 

----------       ----------       ----------

                 new line d

line a-----------line a-----------line a

                                 new line e

  line b-----------line b-----------line b

                                  new line f

  line c-----------line c-----------line c

                 new line g

In the above table, changes are aligned. lines in the commit C are our references. Git compares the neighbor of the reference lines. In the example, we have 4 slots:

above the line a : commit e adds new line d

below the line a : commit f adds new line e

below the line b : commit e adds new line f

below the line c : commit g adds new line g

Here, only one of the branches (commit E, commit F) may add something new or both of them may add the same thing. Otherwise, A merge conflict will occur.

For more information on Git, you can join git training.

Browse Categories

...