# Diff

> Tree-to-tree and index-to-worktree diffs, blob patches, and the DiffEntry model the grit CLI renders.

Diffing in grit-lib centers on the [`diff`](https://docs.rs/grit-lib/latest/grit_lib/diff/index.html) domain module (tree/content diff, merge helpers, patch-ids). Prefer `Repository::diff` (`Diff`) for tree, index, and worktree comparisons on one open handle. Results are `DiffEntry` rows with a `DiffStatus` letter (`M`, `A`, `D`, …), paths, modes, and object ids — the same shape [`grit diff`](https://grit-scm.com/docs/diff/index.md) and `porcelain::status` use before formatting output. See [API layout](https://grit-scm.com/docs/library/api-layout/index.md) for the flat-path map.

Two public structs carry per-file diff output: [`FileDiff`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileDiff.html) from [`Diff::files`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.files) always includes structured hunks when line diff ran; [`ListedFileDiff`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.ListedFileDiff.html) from [`Diff::files_for_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.files_for_entries) is the stat-or-patch row where structured hunks and line counts are filled according to [`DiffDetail`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.DiffDetail.html).

## Entry points

Every diff is a method on the [`Diff`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html) handle from `repo.diff()`. The metadata diffs list changed paths without loading contents. They take one [`TreeDiffOptions`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html) and return a [`DiffEntriesResult`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffEntriesResult.html): the entries, a notice when `diff.renameLimit` skipped inexact rename scoring, and whether an index-to-work-tree scan refreshed stat data. Configuration (`diff.renameLimit`, attributes, `core.autocrlf`, thread settings) is read from the repository inside the handle.

| Method | Compares | Git equivalent |
| --- | --- | --- |
| [`tree_to_tree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.tree_to_tree) | two trees (either may be the empty tree) | `git diff-tree -r A B` |
| [`commits`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.commits) | the trees of two commits | `git diff-tree -r A B` on commits |
| [`index_to_tree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.index_to_tree) | the index against a tree | `git diff --cached` |
| [`index_to_worktree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.index_to_worktree) | the work tree against the index | `git diff-files` |
| [`tree_to_worktree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.tree_to_worktree) | the work tree against a tree, through the index | `git diff <tree>` |
| [`detect_renames`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.detect_renames) | pairs entries you already have | `diffcore` rename, copy and break passes |

`TreeDiffOptions::default()` compares every path and pairs nothing. Its fields, each with a `with_<field>` setter:

| Field | Meaning |
| --- | --- |
| [`renames`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.renames) | [`RenameDetection::Similarity(n)`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.RenameDetection.html) is Git `-M<n>`; `Similarity(100)` pairs identical content only |
| [`copies`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.copies) | [`CopyDetection::Similarity(n)`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.CopyDetection.html) is `-C<n>` (sources are paths changed in the same diff); `FindHarder(n)` adds `--find-copies-harder` (every old path is a source) |
| [`break_rewrites`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.break_rewrites) | [`BreakRewrites::DEFAULT`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.BreakRewrites.html) is a bare `-B`; with renames or copies on, broken pairs are split so their halves can pair elsewhere |
| [`pathspec`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.pathspec) | a [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html); tree walks skip directories it cannot reach and work-tree scans read only the paths it selects |
| [`show_tree_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.show_tree_entries) | also report changed subtrees (`diff-tree -t`); tree and commit diffs |
| [`prefix`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.prefix) | prepended to reported paths when the trees are subtrees; tree and commit diffs |
| [`submodules`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.submodules) | [`SubmoduleIgnoreMode`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.SubmoduleIgnoreMode.html) (`--ignore-submodules=none|untracked|dirty|all`); `All` omits gitlink paths |
| [`threads`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.threads) | a [`ThreadPolicy`](https://docs.rs/grit-lib/latest/grit_lib/parallel/struct.ThreadPolicy.html) for rename scoring and stat workers; `None` uses the repository's |
| [`refresh_index_stat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.refresh_index_stat), [`for_status`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.for_status) | index-to-work-tree only: adopt fresh stat data in the same scan, and status shortcuts that skip reading files whose size changed |

```rust
use grit_lib::diff::{CopyDetection, RenameDetection, TreeDiffOptions};
use grit_lib::worktree::pathspec::{Pathspec, PathspecGlobalFlags};

// `git diff-tree -r -M50 -C50 --find-copies-harder old new -- src/`
let options = TreeDiffOptions::default()
    .with_renames(RenameDetection::Similarity(50))
    .with_copies(CopyDetection::FindHarder(50))
    .with_pathspec(Some(Pathspec::scoped(["src/"], PathspecGlobalFlags::default())));
let result = repo.diff().tree_to_tree(Some(&old_tree), Some(&new_tree), &options)?;
if let Some(skipped) = &result.inexact_rename_skipped {
    eprintln!("raise diff.renameLimit to {}", skipped.suggested_limit);
}
for entry in &result.entries {
    println!("{}\t{}", entry.status.letter(), entry.path());
}
```

The content methods turn entries into hunks and line counts under a [`DiffOptions`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffOptions.html): [`files_for_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.files_for_entries) at any [`DiffDetail`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.DiffDetail.html), [`for_each_file`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.for_each_file) one patch row at a time, [`stat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.stat) for a [`DiffStat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html), and [`structured`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.structured) / [`for_each_structured`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.for_each_structured) for [`TreeDiffStructured`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffStructured.html) rows in input order. [`commit_files`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.commit_files) diffs one commit against its parents (`grit show`), [`object_changes`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.object_changes) loads both sides of stored-object entries, and [`hunk_bundle`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.hunk_bundle) gathers unstaged hunks for hunk-level staging.

## Pickaxe

[`Pickaxe`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html) implements Git's pickaxe filters for revision walks: [`Pickaxe::occurrences`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html#method.occurrences) (`-S`, occurrence-count change per file) and [`Pickaxe::line_grep`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html#method.line_grep) (`-G`, regex on added/removed lines). Call [`Pickaxe::matches_commit`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html#method.matches_commit) to test one commit against its first parent; wire the filter through [`RevWalkListOptions::pickaxe`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.RevWalkListOptions.html) for `grit log` / `grit revs`.

## Choosing what to compare

[`Diff::resolve_request`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.resolve_request) turns diff operands as a user typed them ([`DiffRequest`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffRequest.html): `--staged`, `--unstaged`, `--against`, operands before and after `--`, and pathspec-file entries) into a [`DiffTarget`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.DiffTarget.html) plus a [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html) on [`DiffArguments::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffArguments.html#structfield.pathspec). This is the resolver [`grit diff`](https://grit-scm.com/docs/commands/diff.md/index.md) uses. Operands that are not revisions but name known paths become pathspecs, so `file.txt` and `HEAD~1 file.txt` need no `--`. One revision selects that commit's own patch, `A..B` and `A...B` select a tree diff (merge base of `A` and `B` against `B` for three dots), and two revisions compare their trees. Failures are typed [`ResolveDiffArgumentsError`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.ResolveDiffArgumentsError.html) variants: flag conflicts, `UnresolvedRevision` (carrying the library cause), `NotACommit`, `NoMergeBase`, and pathspec errors. When explicit paths or pathspec-file entries accompany an unresolved revision, the resolver returns `UnresolvedRevision`; only a lone unresolved operand without path limits falls back to a worktree path. Hand the target and path limit to [`Diff::files`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.files) (`&Pathspec`) for structured file diffs. [`Diff::resolve_pathspec`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.resolve_pathspec) returns a [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html) for commit diffs on their own (as `grit show` and `grit log -p` do), without requiring the paths to exist in the checkout.

## Tree-to-tree

[`Diff::tree_to_tree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.tree_to_tree) reads tree metadata only and prunes identical subtree object ids without opening them. The walk retains active directory frames and the ODB’s bounded parsed-tree cache; completed siblings do not accumulate in a second cache, and trees read for that cache are not also copied into the ODB’s raw-object cache. The returned entries own changed paths, modes and ids, so result memory still grows with the number of changes. Rename, copy and break pairing run only when `TreeDiffOptions` asks for them; when a list has no added/deleted pair to score, rename detection returns it unchanged without reading content. [`Diff::files_for_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.files_for_entries) applies [`DiffOptions::renames`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffOptions.html#structfield.renames) (default similarity 50, Git `-M`) before stat or patch work; pass [`RenameDetection::Off`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.RenameDetection.html#variant.Off) when the entries are already paired. For metadata-only output, [`FileDiff::from_metadata`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.ListedFileDiff.html#method.from_metadata) builds a row from one entry without line-diff blob reads. Diff lists are in Git’s order, raw path bytes; [`sort_entries_by_path`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.sort_entries_by_path.html) restores that order after filtering or merging lists and costs one comparison pass when the list is already ordered. See the [tree metadata measurements](https://grit-scm.com/docs/benchmarks/index.md#tree-metadata-diff-2026-10-27) and the [CLI follow-up](https://grit-scm.com/docs/benchmarks/index.md#tree-metadata-diff-through-the-cli-2026-10-27).

[`Diff::commits`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.commits) resolves each commit’s tree and diffs them the same way; it returns `RefError::Invalid` (as `Error::Ref`) when an id is not a commit.

## Index-to-worktree

[`Diff::index_to_worktree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.index_to_worktree) compares the files on disk with the index. Entries whose stat data matches are not read, and racily clean entries (modified within the index file's timestamp) are hashed to be sure. The work-tree side of a changed file carries a null `new_oid` unless its content had to be hashed. Gitlinks follow [`TreeDiffOptions::submodules`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.submodules). With [`refresh_index_stat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.TreeDiffOptions.html#structfield.refresh_index_stat) the in-memory index adopts fresh stat data for unchanged entries in the same scan, and [`DiffEntriesResult::index_stat_refreshed`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffEntriesResult.html#structfield.index_stat_refreshed) says whether writing it back is worthwhile. [`Diff::tree_to_worktree`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.tree_to_worktree) compares the work tree with any tree through the index, reading work-tree bytes through attributes and clean filters. Both return [`RepositoryError::RequiresWorkTree`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.RequiresWorkTree) in a bare repository.

## Staged, unstaged, and working-tree changes

[`Diff::uncommitted`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.uncommitted) loads the index once and returns an [`UncommittedDiff`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html) for the comparisons `grit diff` makes without revisions. [`staged_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html#method.staged_entries) compares the index with `HEAD`'s tree, [`unstaged_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html#method.unstaged_entries) compares the working tree with the index, and [`worktree_entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html#method.worktree_entries) compares the working tree and index together with any tree (`HEAD`'s for `grit diff`, another revision's for `--against`). Each returns sorted `DiffEntry` rows without reading blob content, so filter them by pathspec first and then load only what you need. [`load_worktree_changes`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html#method.load_worktree_changes) reads new sides from the working tree (clean filters and line-ending rules applied, a gitlink shown as its checked-out commit with `-dirty` when modified); [`Diff::object_changes`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.object_changes) reads both sides from the object database in parallel, for staged or tree entries. Both return [`FileChange`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileChange.html) rows, which give structured hunks with [`structured`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileChange.html#method.structured) or line counts with [`line_stat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileChange.html#method.line_stat). One `UncommittedDiff` reuses its index and worktree rules across all of these calls. The working-tree methods return [`RepositoryError::RequiresWorkTree`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.RequiresWorkTree) (as [`Error::Repository`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Repository)) in a bare repository, and [`Diff::resolve_request`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.resolve_request) rejects a working-tree target there with `ResolveDiffArgumentsError::NoWorkTree`.

To go straight from a resolved [`DiffTarget`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.DiffTarget.html) to its changed paths, call [`UncommittedDiff::entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html#method.entries) with the target, a [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html), and a `DiffOptions`: it picks the comparison above (with `HEAD`'s tree for `WorktreeVsHead`), keeps the entries within the pathspecs, and applies [`DiffOptions::filter`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffOptions.html#structfield.filter) (Git `--diff-filter`) after rename detection. Load the result on the same handle. For commit and range targets, [`Diff::entries`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.entries) does the same without reading the index. This is how `grit diff` and `grit diff --patch-text` choose their entries. To give staged and unstaged hunks stable ids, [`UncommittedDiff::peer_changes`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UncommittedDiff.html#method.peer_changes) loads the changes on the other side of the index for the same paths, ready to pass as the peer hunks of [`hunk_ids`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.hunk_ids.html).

## Blob diffs

For a single modified file, read old and new bytes from [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html) and pass them to [`unified_diff`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.unified_diff.html) (see [Text diffs](#text-diffs)) or the structured helpers in [`structured`](https://docs.rs/grit-lib/latest/grit_lib/diff/structured/index.html). For tree diffs meant for `git apply`, stream [`write_patch`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.write_patch.html) over a `DiffEntry` slice with [`PatchTextOptions`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.PatchTextOptions.html) (same headers and `GIT binary patch` bodies as `git diff --binary`). For index and work-tree diffs, [`write_patch_resolved`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.write_patch_resolved.html) takes [`PatchResolvedSide`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.PatchResolvedSide.html) values whose sides are a [`PatchSide`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.PatchSide.html): bytes you already hold, a blob in the object database, or the work-tree file (read through clean filters and line-ending rules). Binary files get full ids of the written content on their `index` line, which `git apply` requires. Line-level hunks honor one shared [`DiffOptions`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffOptions.html) value (algorithm, context, indent heuristic, renames, optional word-level inline emphasis) whether you emit unified patch text or structured hunks for the CLI. Defaults match Git (`Myers`, `-U3`, indent heuristic on, rename similarity 50). Patch writers load `.gitattributes` once per diff (work tree, `info/attributes`, `GIT_ATTR_SOURCE`, and `attr.tree`, matching `git diff`) and resolve each path's `diff` driver for `@@` function-name suffixes and structured `hunks[].context`. Commit-tree patches (`git show` / `git log -p`) use the commit tree's attributes instead. The CLI builds human, `--json`, and `--markdown` views from `DiffEntry` lists plus structured or unified bodies; [`grit diff --patch-text`](https://grit-scm.com/docs/commands/diff.md/index.md) calls `write_patch` for revisions and `write_patch_resolved` for staged and work-tree changes.

## Text diffs

[`unified_diff`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.unified_diff.html) turns two strings into a unified patch, and [`line_change_counts`](https://docs.rs/grit-lib/latest/grit_lib/diff/fn.line_change_counts.html) counts the `+` and `-` lines of that same patch without building it. Both take one [`UnifiedDiffOptions`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html), whose defaults are Git's: Myers alignment, three context lines, the indent heuristic, Git's default function-name rule and `\ No newline at end of file` markers. The output matches `git diff --no-index` with the same options byte for byte, from the `---` line on. `grit-lib/tests/text_diff_options.rs` checks this against the system `git` for every option.

```rust
use grit_lib::diff::{unified_diff, DiffAlgorithm, UnifiedDiffOptions, WhitespaceMode};

let options = UnifiedDiffOptions::new()
    .with_paths("src/lib.rs", "src/lib.rs")
    .with_algorithm(DiffAlgorithm::Histogram)
    .with_whitespace(WhitespaceMode::ignore_space_change());
let patch = unified_diff(&old_text, &new_text, &options);
```

| Option | Git | Field |
| --- | --- | --- |
| `---` / `+++` labels | `--src-prefix`, `--dst-prefix`, `--no-prefix` | [`old_label`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.old_label), [`new_label`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.new_label) ([`DiffLabel`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.DiffLabel.html)); unset means hunks only |
| Path quoting | `core.quotePath` | [`path_quoting`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.path_quoting) ([`PathQuoting`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.PathQuoting.html)) |
| Context | `-U<n>`, `--inter-hunk-context` | [`context_lines`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.context_lines), [`inter_hunk_context`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.inter_hunk_context) |
| Function context | `-W` | [`extent`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.extent) ([`HunkExtent::Function`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.HunkExtent.html#variant.Function)) |
| Hunk-header function names | `diff.<driver>.xfuncname` | [`funcname`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.funcname), a matcher from [`userdiff`](https://docs.rs/grit-lib/latest/grit_lib/diff/userdiff/index.html) |
| Algorithm | `--diff-algorithm` | [`algorithm`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.algorithm) ([`DiffAlgorithm`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.DiffAlgorithm.html)) |
| Indent heuristic | `--[no-]indent-heuristic` | [`indent_heuristic`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.indent_heuristic) ([`IndentHeuristic`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.IndentHeuristic.html)) |
| Anchors | `--anchored=<text>` | [`anchors`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.anchors); non-empty anchors use patience alignment, as in Git |
| Whitespace | `-w`, `-b`, `--ignore-space-at-eol`, `--ignore-blank-lines` | [`whitespace`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.whitespace) ([`WhitespaceMode`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.WhitespaceMode.html)) |
| No-newline markers | always on | [`no_newline_marker`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.UnifiedDiffOptions.html#structfield.no_newline_marker) ([`NoNewlineMarker`](https://docs.rs/grit-lib/latest/grit_lib/diff/enum.NoNewlineMarker.html)) |

When equal sides, or a whitespace rule, leave no hunk, `unified_diff` returns an empty string, labels included, as Git prints nothing. `UnifiedDiffOptions::from(&diff_options)` carries the line settings of a repository [`DiffOptions`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffOptions.html) over to a text diff. Under whitespace rules the patch compares normalized lines but shows the original text, with context lines from the new side. Anchors pin a line that starts with one of the given prefixes and occurs exactly once on each side, so it stays as context instead of showing up as removed and re-added.

For combined (`--cc`) patches of a merge path, [`format_combined_textconv_patch`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_diff/fn.format_combined_textconv_patch.html) takes a [`CombinedPatchOptions`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_diff/struct.CombinedPatchOptions.html), and [`format_worktree_conflict_combined`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_diff/fn.format_worktree_conflict_combined.html) takes the three index stages of a conflicted path as [`ConflictStages`](https://docs.rs/grit-lib/latest/grit_lib/merge/merge_diff/struct.ConflictStages.html).

## Diffstat

[`DiffStat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html) is the data behind `--stat`, `--numstat` and `--shortstat`. [`Diff::stat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.stat) builds one for a list of entries. [`DiffStat::from_files`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html#method.from_files) takes the rows from `Diff::files_for_entries` at any detail level: each row's counts come from [`FileDiff::line_stat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.ListedFileDiff.html#method.line_stat), which uses the stat when one was computed and otherwise counts the structured or combined hunk lines, so a patch-mode listing and a stat-mode listing give the same diffstat. [`totals`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html#method.totals) sums the rows. To draw bars, scale each row with [`LineStat::bar`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.LineStat.html#method.bar) against [`max_changes`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html#method.max_changes) and a column budget; the returned [`StatBar`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.StatBar.html) gives `+` and `-` column counts. `grit diff --stat`, `grit show`, `grit log --stat` and `grit stash show` render this model.

```rust
use grit_lib::diff::{DiffOptions, TreeDiffOptions};

let entries = repo
    .diff()
    .tree_to_tree(Some(&old_tree), Some(&new_tree), &TreeDiffOptions::default())?
    .entries;
// `DiffOptions::default()` pairs renames at Git's -M50 before counting lines. When the
// entries are already rename-aware, pass `DiffOptions::default().with_renames(RenameDetection::Off)`.
let stat = repo.diff().stat(entries, &DiffOptions::default())?;
for file in stat.files() {
    let bar = file.lines.bar(stat.max_changes(), 40);
    println!("{} | {}{}", file.path, "+".repeat(bar.plus), "-".repeat(bar.minus));
}
let totals = stat.totals();
println!("{} files, +{} -{}", totals.files_changed, totals.insertions, totals.deletions);
```

Under any whitespace rule (`-w`, `-b`, `--ignore-space-at-eol`, `--ignore-blank-lines`), Git leaves out of `--stat` any modified text file whose changes were all ignored. [`FileDiff::changes_all_ignored`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.ListedFileDiff.html#method.changes_all_ignored) tells you which rows those are. Additions, deletions, renames, mode changes and binary files stay listed. For a stash, [`RepositoryStash::diff_stat`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryStash.html#method.diff_stat) returns the finished `DiffStat` of `stash@{n}` against its base (`git stash show --stat`). It counts lines without building hunks and applies that whitespace rule.

For history listings, [`Diff::commit_files_many`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.commit_files_many) diffs a batch of commits against their first parents in parallel, reusing each parent tree when the commits are newest-first linear history; `grit log --stat`, `--numstat` and `-p` use it. When you only need per-commit counts, [`Diff::commit_line_totals`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.commit_line_totals) returns one [`DiffTotals`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffTotals.html) per commit (the numbers in `git log --shortstat`), limited to the [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html) you pass. Merges are not diffed and get `None`; a root commit is compared with the empty tree. A terminal `grit log` draws these as the `+added -removed` column and hides commits whose totals are zero.

## Porcelain models

- **Status** — combines index vs HEAD and index vs worktree scans into structured sections (the CLI maps them to default / `--json` / `--markdown` output).
- **Add** — uses diff results to decide which paths to hash and stage.
- **Diff command** — tree-to-tree for commit ranges, index-to-worktree for uncommitted changes, then blob-level rendering for text files.

## Example

The program below diffs the latest commit against its parent (tree-to-tree), checks whether the work tree is dirty, and counts unified-diff lines for one modified blob:

```rust
//! Tree-to-tree, index-to-worktree, and blob diffs used by porcelain and the CLI.
//!
//! Source for the library guide "Diff" page (included in the docs site).

use anyhow::Result;
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::diff::{unified_diff, DiffEntry, DiffStatus, TreeDiffOptions, UnifiedDiffOptions};
use grit_lib::repo::Repository;

use std::path::{Path, PathBuf};

fn open_repo(root: &Path) -> Result<Repository> {
    let git_dir = if root.join(".git").is_dir() {
        root.join(".git")
    } else {
        root.to_path_buf()
    };
    let work_tree = if root.join(".git").is_dir() {
        Some(root)
    } else {
        None
    };
    let mut opts = RepositoryOptions::from_process();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Ok(Repository::open(&git_dir, &opts)?)
}

fn print_name_status(entries: &[DiffEntry]) {
    for entry in entries {
        let letter = entry.status.letter();
        let path = entry.path();
        if entry.status == DiffStatus::Renamed {
            if let (Some(old), Some(new)) = (&entry.old_path, &entry.new_path) {
                println!("{letter}\t{old}\t{new}");
                continue;
            }
        }
        println!("{letter}\t{path}");
    }
}

fn main() -> Result<()> {
    let root = std::env::args()
        .nth(1)
        .map(PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .ok_or_else(|| anyhow::anyhow!("missing repository path"))?;
    let repo = open_repo(&root)?;

    let head = repo.references().head()?;
    let new_commit = head
        .oid()
        .cloned()
        .ok_or_else(|| anyhow::anyhow!("HEAD has no commit"))?;
    let new_commit_data = repo.objects().read_commit(&new_commit)?;
    let parent = new_commit_data
        .parents
        .first()
        .copied()
        .ok_or_else(|| anyhow::anyhow!("need a commit with a parent"))?;

    let old_tree = repo.objects().commit_tree(&parent)?;
    let new_tree = new_commit_data.tree;

    let tree_changes = repo
        .diff()
        .tree_to_tree(
            Some(&old_tree),
            Some(&new_tree),
            &TreeDiffOptions::default(),
        )?
        .entries;
    println!("tree_diff_begin");
    print_name_status(&tree_changes);
    println!("tree_diff_end");

    if repo.work_tree().is_some() {
        let mut index = repo
            .index()
            .load(&grit_lib::index::IndexLoadOptions::default())?;
        let wt_changes = repo.diff().index_to_worktree(
            &mut index,
            &TreeDiffOptions::default(),
            &mut grit_lib::progress::NullProgress,
            &grit_lib::progress::CancelToken::never(),
        )?;
        println!("index_worktree_dirty={}", !wt_changes.entries.is_empty());
    }

    if let (Some(entry),) = (tree_changes.first(),) {
        if entry.status == DiffStatus::Modified {
            let old_blob = repo.odb().read(&entry.old_oid)?.data;
            let new_blob = repo.odb().read(&entry.new_oid)?.data;
            let old_text = String::from_utf8_lossy(&old_blob);
            let new_text = String::from_utf8_lossy(&new_blob);
            let old_path = entry.old_path.as_deref().unwrap_or(entry.path());
            let new_path = entry.new_path.as_deref().unwrap_or(entry.path());
            let options = UnifiedDiffOptions::new().with_paths(old_path, new_path);
            let patch = unified_diff(&old_text, &new_text, &options);
            let hunk_lines = patch
                .lines()
                .filter(|l| l.starts_with('-') || l.starts_with('+'))
                .count();
            println!("blob_unified_hunk_lines={hunk_lines}");
        }
    }

    Ok(())
}
```

Requires a repository whose `HEAD` has a parent (at least two commits):

```bash
cargo run --bin guide_diff /path/to/repo
git -C /path/to/repo diff --name-status HEAD~1 HEAD
```
