Git - Merging 'add' from two branches

58 views Asked by At
  1. I have Branch1 and Branch2, and have added a file with same name in both branches. Say Branch1\folder\file.txt and Branch2\folder\file.txt.
  2. I merge Branch1 into Branch2 and get an expected merge conflict on the file.
  3. I select Branch1 version of the file, commit and push.

When I see history of the file in Branch2 I see that the file is 'add'ed and instead of 'modified'. I expect modified because the file was already present in Branch2 and was updated by the file from Branch1 but Git history doesn't reflect this.

Is this by design? Is there any another way of achieving the same result with correct/desired history?

1

There are 1 answers

2
LightBender On BEST ANSWER

Background Information

Unlike most other version control systems, git does not track files, but instead it tracks content. Each commit is a large snapshot of the code, which means that you are guaranteed to get back exactly what you put in, bit for bit. The file data we use to organize and understand the snapshot is more like metadata inside the git model.

When you compare two commits, even if there are 30 commits between them, git only looks at the two commits you are comparing. As a result, it needs a set of rules for how to interpret the metadata when it sees content being moved around and modified.

So it seeing a file as added, deleted, moved, modified, etc, is not from it reading a log of your actions, but by comparing two snapshots and interpreting the difference.

To Answer Your Question

This is by design because git sees the history as a comparison of two snapshots rather than a series of discreet human actions.

Here is a diagram of the scenario you described. (Arrows point from child to parent)

enter image description here

Comparing each pair of commits below, git will interpret file.txt as:

A > B : Added
A > C : Added
B > D : Modified
C > D : Unchanged
A > D : Added