2

Given two files how does git diff or any diff tool tell which lines have been added, modified or deleted?

Are there any edge cases where it may fail to recognise the correct status of the edited line?

EDIT: This question is more concerned with the actual method of how the diffing happens

Salim
  • 439
  • 2
  • 8
  • 1
    _Does_ git show lines as "changed", ever? Or are they deleted and added? – CodeCaster Jan 06 '20 at 14:36
  • Each commit references a tree of files. To output diff between commits A and B, git compares commit A's tree and commit B's tree. – Romain Valeri Jan 06 '20 at 14:38
  • 1
    Have a look at a [related post](https://unix.stackexchange.com/questions/498581/how-to-tell-the-difference-between-changed-and-added-lines). – Axel Kemper Jan 06 '20 at 14:39
  • This doesn't really have anything to do with `git`, but with diff algorithms in general. `git` just supplies the input files to whatever `diff` tool you use. – chepner Jan 06 '20 at 15:09

2 Answers2

4

Git stores snapshots: given any two snapshots of your choice, Git extracts the files you'd like compared1 to a temporary area2 and then runs a "diff engine" on the two files. The result of this engine is, or should be, a series of instructions that, when applied, will convert the left-side file to the right-side file.

Git has several built-in diff engines, which Git calls:

It can also run your chosen external diff engine.


1Or at least, the ones it wants to compare. If you are comparing files that are not actually in commits, they may already be extracted.

2Git mostly does this in-memory, but when running an external diff, really does use temporary files.

torek
  • 448,244
  • 59
  • 642
  • 775
0

git keeps the current committed version of every single file in the repo. If a file is modified, then the committed version is generated and compared with the current version of your file. It is then the same as diff'ing two files on the hard drive. If the diff tool can diff two ordinary files, then it can diff the version that git produced and the version that you have.

Unless if there is some really obscure bug, the diff tool should be able to catch any difference, as the diff tool compares the two files line by line.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740