grit
CLILibrary
HEAD → docs/library/diff
Library guide / DiffMarkdown

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 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 and porcelain::status use before formatting output. See API layout for the flat-path map.

Two public structs carry per-file diff output: FileDiff from Diff::files always includes structured hunks when line diff ran; ListedFileDiff from Diff::files_for_entries is the stat-or-patch row where structured hunks and line counts are filled according to DiffDetail.

Entry points

Every diff is a method on the Diff handle from repo.diff(). The metadata diffs list changed paths without loading contents. They take one TreeDiffOptions and return a DiffEntriesResult: 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 two trees (either may be the empty tree) git diff-tree -r A B
commits the trees of two commits git diff-tree -r A B on commits
index_to_tree the index against a tree git diff --cached
index_to_worktree the work tree against the index git diff-files
tree_to_worktree the work tree against a tree, through the index git diff <tree>
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 RenameDetection::Similarity(n) is Git -M<n>; Similarity(100) pairs identical content only
copies CopyDetection::Similarity(n) 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 BreakRewrites::DEFAULT is a bare -B; with renames or copies on, broken pairs are split so their halves can pair elsewhere
pathspec a Pathspec; tree walks skip directories it cannot reach and work-tree scans read only the paths it selects
show_tree_entries also report changed subtrees (diff-tree -t); tree and commit diffs
prefix prepended to reported paths when the trees are subtrees; tree and commit diffs
submodules SubmoduleIgnoreMode (`--ignore-submodules=none
threads a ThreadPolicy for rename scoring and stat workers; None uses the repository's
refresh_index_stat, 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
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: files_for_entries at any DiffDetail, for_each_file one patch row at a time, stat for a DiffStat, and structured / for_each_structured for TreeDiffStructured rows in input order. commit_files diffs one commit against its parents (grit show), object_changes loads both sides of stored-object entries, and hunk_bundle gathers unstaged hunks for hunk-level staging.

Pickaxe

Pickaxe implements Git's pickaxe filters for revision walks: Pickaxe::occurrences (-S, occurrence-count change per file) and Pickaxe::line_grep (-G, regex on added/removed lines). Call Pickaxe::matches_commit to test one commit against its first parent; wire the filter through RevWalkListOptions::pickaxe for grit log / grit revs.

Choosing what to compare

Diff::resolve_request turns diff operands as a user typed them (DiffRequest: --staged, --unstaged, --against, operands before and after --, and pathspec-file entries) into a DiffTarget plus a Pathspec on DiffArguments::pathspec. This is the resolver grit diff 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 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 (&Pathspec) for structured file diffs. Diff::resolve_pathspec returns a Pathspec 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 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 applies DiffOptions::renames (default similarity 50, Git -M) before stat or patch work; pass RenameDetection::Off when the entries are already paired. For metadata-only output, FileDiff::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 restores that order after filtering or merging lists and costs one comparison pass when the list is already ordered. See the tree metadata measurements and the CLI follow-up.

Diff::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 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. With refresh_index_stat the in-memory index adopts fresh stat data for unchanged entries in the same scan, and DiffEntriesResult::index_stat_refreshed says whether writing it back is worthwhile. Diff::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 in a bare repository.

Staged, unstaged, and working-tree changes

Diff::uncommitted loads the index once and returns an UncommittedDiff for the comparisons grit diff makes without revisions. staged_entries compares the index with HEAD's tree, unstaged_entries compares the working tree with the index, and 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 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 reads both sides from the object database in parallel, for staged or tree entries. Both return FileChange rows, which give structured hunks with structured or line counts with line_stat. One UncommittedDiff reuses its index and worktree rules across all of these calls. The working-tree methods return RepositoryError::RequiresWorkTree (as Error::Repository) in a bare repository, and Diff::resolve_request rejects a working-tree target there with ResolveDiffArgumentsError::NoWorkTree.

To go straight from a resolved DiffTarget to its changed paths, call UncommittedDiff::entries with the target, a Pathspec, and a DiffOptions: it picks the comparison above (with HEAD's tree for WorktreeVsHead), keeps the entries within the pathspecs, and applies DiffOptions::filter (Git --diff-filter) after rename detection. Load the result on the same handle. For commit and range targets, Diff::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 loads the changes on the other side of the index for the same paths, ready to pass as the peer hunks of hunk_ids.

Blob diffs

For a single modified file, read old and new bytes from Odb and pass them to unified_diff (see Text diffs) or the structured helpers in structured. For tree diffs meant for git apply, stream write_patch over a DiffEntry slice with PatchTextOptions (same headers and GIT binary patch bodies as git diff --binary). For index and work-tree diffs, write_patch_resolved takes PatchResolvedSide values whose sides are a PatchSide: 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 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 calls write_patch for revisions and write_patch_resolved for staged and work-tree changes.

Text diffs

unified_diff turns two strings into a unified patch, and line_change_counts counts the + and - lines of that same patch without building it. Both take one UnifiedDiffOptions, 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.

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, new_label (DiffLabel); unset means hunks only
Path quoting core.quotePath path_quoting (PathQuoting)
Context -U<n>, --inter-hunk-context context_lines, inter_hunk_context
Function context -W extent (HunkExtent::Function)
Hunk-header function names diff.<driver>.xfuncname funcname, a matcher from userdiff
Algorithm --diff-algorithm algorithm (DiffAlgorithm)
Indent heuristic --[no-]indent-heuristic indent_heuristic (IndentHeuristic)
Anchors --anchored=<text> anchors; non-empty anchors use patience alignment, as in Git
Whitespace -w, -b, --ignore-space-at-eol, --ignore-blank-lines whitespace (WhitespaceMode)
No-newline markers always on no_newline_marker (NoNewlineMarker)

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 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 takes a CombinedPatchOptions, and format_worktree_conflict_combined takes the three index stages of a conflicted path as ConflictStages.

Diffstat

DiffStat is the data behind --stat, --numstat and --shortstat. Diff::stat builds one for a list of entries. DiffStat::from_files takes the rows from Diff::files_for_entries at any detail level: each row's counts come from FileDiff::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 sums the rows. To draw bars, scale each row with LineStat::bar against max_changes and a column budget; the returned StatBar gives + and - column counts. grit diff --stat, grit show, grit log --stat and grit stash show render this model.

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 tells you which rows those are. Additions, deletions, renames, mode changes and binary files stay listed. For a stash, RepositoryStash::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 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 returns one DiffTotals per commit (the numbers in git log --shortstat), limited to the Pathspec 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.