git auto-merge does not work as expected

1.7k views Asked by At

I happen to have a file (say abc) in two branches: master and sample.

The commit date for abc on sample is older than abc on current master; in other words abc is latest on master.

Now, I ran:

git checkout sample
git merge master 

It auto-merged several files (including abc).

Problem: Line#42 in abc seems to persist from branch sample instead getting replaced from master.

Why is this happening ? I was quite expecting otherwise. Please help.

2

There are 2 answers

5
Michael Ivko On

The fact that abc is newer on master than on sample doesn't means it gets wholly replaced by the master version during merge. If sample's version of abc has some changes that are not present on master, even if they are older than the last change in master, git will try to preserve them during merge.

0
David Deutsch On

It is important to keep in mind that, when merging, Git does not operate on the file level; rather, it operates on the line level. If a line was changed in sample but not in master (or in master but not in sample), that change will be in the merge of the two branches.

To see why Git does this, consider the following scenario:

  1. sample is branched from master
  2. Person X changes line 42 in ABC on sample
  3. Person Y changes line 54 in ABC on master
  4. The branches are merged

If Git merged the way you expected, then person X's changes would have been lost in this case. By checking line-by-line, Git preserves as many changes as possible. Note that if both person X and person Y had changed line 42, the merge would have resulted in a conflict, no matter what order the changes were made in.