Skip to main content

Module diff

Module diff 

Source
Expand description

Tree and content diffs, rename detection, merge diffs, and related helpers.

Library guide: mod

use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let _repo = Repository::init(dir.path(), &InitOptions::default())?;
let _ = _repo.diff();

Re-exports§

pub use handle::Diff;
pub use has_changes::text_sides_differ;
pub use hunk_id::hunk_ids;
pub use hunk_id::hunk_ids_with_duplicate_peers;
pub use hunk_id::peer_hunks_by_primary_path;
pub use hunk_id::peer_scope_includes_path;
pub use hunk_id::DiffSide;
pub use hunk_id::HunkId;
pub use hunk_id::HunkIdError;
pub use pickaxe::Pickaxe;
pub use pickaxe::PickaxeError;
pub use pickaxe::PickaxeKind;

Modules§

bloom
bloom API (re-exported at this path).
combined_diff_patch
combined_diff_patch API (re-exported at this path).
combined_tree_diff
combined_tree_diff API (re-exported at this path).
fmt_merge_msg
fmt_merge_msg API (re-exported at this path).
handle
Repository-scoped tree and index diffs via Diff.
hunk_id
Stable identifiers for structured diff hunks (patch selection in later steps).
merge_diff
merge_diff API (re-exported at this path).
merge_file
merge_file API (re-exported at this path).
merge_trees
merge_trees API (re-exported at this path).
patch_ids
patch_ids API (re-exported at this path).
pickaxe
Pickaxe filters (-S / -G) for revision walks and diffs.
rerere
rerere API (re-exported at this path).
structured
Structured line diffs for CLI and embedders (grit diff, grit show).
userdiff
userdiff API (re-exported at this path).
ws
ASCII whitespace helpers used by the diff engine.

Structs§

CommitFilesManyInput
One commit’s identity for Diff::commit_files_many_work, avoiding a second ODB read.
CommitFilesManyOptions
Options for Diff::commit_files_many.
CommitFilesResult
One commit’s diff output in Diff::commit_files_many (same order as input oids).
DetectRenamesOptions
Options for detect_renames_with_policy.
DiffArguments
Resolved diff mode and normalized pathspecs.
DiffEntriesResult
Tree or commit diff entries after rename detection, with an optional limit notice.
DiffEntry
A single diff entry representing one changed path.
DiffFilesOutput
Output of build_file_diffs.
DiffFilter
Typed include/exclude set for DiffStatus using Git’s letter syntax.
DiffIndexToWorktreeOptions
Additional inputs for diff_index_to_worktree_with_options.
DiffOptions
Line-diff options shared by structured output, log patches, and benchmarks.
DiffPostprocessOptions
Options for Git-style rename, copy, and break-rewrite post-processing on tree diffs.
DiffPostprocessWorktree
Index and git directory used to read canonical (clean) worktree bytes during break-rewrite post-processing on tree↔worktree diffs.
DiffRequest
Unparsed grit diff flags and operands, as the user typed them.
DiffStat
Per-file line counts plus totals for a whole diff.
DiffTotals
Summary across all files in a stat-style diff.
DiffTreeToWorktreeExtras
Optional worktree access policy for diff_tree_to_worktree_with_git_dir_and_rules’s slow path.
FileChange
One changed path with both sides’ bytes loaded for diffing.
FileDiff
One changed file with structured hunks and metadata.
FileStat
One file’s row in a DiffStat.
HunkDiffBundle
Staged and unstaged file diffs for hunk id assignment (one staged scan per call).
InexactRenameDetectionSkipped
Emitted when unmatched rename candidates exceed diff.renameLimit after exact and basename pairing.
LineStat
Line insertion/deletion counts for one file (--numstat).
ListedFileDiff
One changed file with optional patch body or line counts.
LogPatchOptions
Options for write_commit_log_patch.
PatchResolvedSide
One file for write_patch_resolved: diff metadata plus where each side’s content is.
PatchTextOptions
Options for write_patch (git diff --binary-compatible output for git apply).
RenameDetectionResult
Result of detect_renames_with_policy.
StatBar
Column counts for one diffstat row’s change bar (see LineStat::bar).
SubmodulePorcelainFlags
Submodule dirty bits aligned with Git’s DIRTY_SUBMODULE_* / porcelain v2 S??? token.
TreeDiffContent
One tree diff entry with both sides loaded for line-level diffing.
TreeDiffStructured
Tree diff entry with structured line hunks ready for CLI rendering.
UncommittedDiff
Staged, unstaged, and working-tree diffs over one loaded index.
UnknownDiffAlgorithm
Unknown value for DiffAlgorithm’s FromStr implementation.
WhitespaceMode
Whitespace handling for line diffs (super::DiffOptions::whitespace).
WorktreeAddRefreshParams
Inputs for classify_worktree_entry_for_add.

Enums§

DiffAlgorithm
Line diff algorithm names matching Git’s diff.algorithm and --diff-algorithm.
DiffDetail
How much content to compute for each changed file.
DiffMerges
How to diff a merge commit’s tree against its parents.
DiffStatus
The kind of change between two sides of a diff.
DiffTarget
What to compare when producing a structured file diff list.
InvalidDiffFilter
Unknown or unsupported --diff-filter letter.
LogPatchBinaryFormat
Binary file encoding inside a log/show patch (git log -p vs git diff --binary).
LogPatchCommitHeader
How much commit metadata precedes each patch in write_commit_log_patch.
NoIndexError
Failure modes specific to diff_paths.
PatchSide
Where write_patch_resolved takes the content of one side of a file.
RenameDetection
Rename detection policy for tree diffs.
ResolveDiffArgumentsError
Invalid grit diff argument combinations or revision parsing failures.
WorktreeAddRefresh
Outcome of comparing a tracked index entry to its worktree path for staging refresh.

Constants§

GIT_DIFF_DEFAULT_BREAK_SCORE
Default break threshold (DEFAULT_BREAK_SCORE in diffcore.h), internal 0–GIT_DIFF_MAX_SCORE scale.
GIT_DIFF_MAX_SCORE
Internal maximum diff score used by Git rename/break heuristics (MAX_SCORE in diffcore.h).
RENAME_DETECTION_DISABLED
u32 rename APIs: thresholds 0–100 run detection at that Git -M percent; RENAME_DETECTION_DISABLED (101) and above skip detection (legacy postprocess and --no-renames plumbing).
WORD_LEVEL_INLINE_MAX_CHANGED_FILES
Changed-file count above which word-level inline emphasis is skipped (human TTY diffs).

Functions§

anchored_unified_diff
Compute a unified diff with anchored lines.
annotate_unified_diff_no_newline_at_eof
Insert Git \ No newline at end of file after -/+ hunk lines when that side of the file lacks a trailing newline on the last line.
apply_diff_filter
Drop entries that do not match filter (Git --diff-filter, after rename detection).
apply_rename_detection_to_diff_entries
Apply Git -M rename detection to a flat diff (index↔tree, tree↔tree, or index↔worktree).
build_file_diffs
Fill per-file diff bodies for tree/index diff entries.
build_file_diffs_streaming
Build patch FileDiff rows one entry at a time without retaining every hunk list.
bytes_for_diff
Classify raw blob bytes for line diffs (NUL in the first 8 KiB ⇒ binary).
classify_worktree_entry_for_add
Decide whether staging must re-read and re-hash a tracked path.
combined_structured_patch_body
Format a CombinedStructuredTextDiff as Git combined patch body bytes.
commit_diff_files
Build per-file diffs for one commit, using combined merge diff when requested.
count_changes_git_histogram
Count insertions and deletions using Git’s histogram line-diff engine.
count_changes_with_algorithm
Count insertions and deletions using the given line-diff algorithm.
count_git_lines
Line count for diffstat/--numstat, matching Git’s count_lines() in diff.c.
detect_copies
Detect copies among diff entries.
detect_copies_with_policy
Like detect_copies, but honors parallel thread policy and rename limits.
detect_renames
Detect renames by pairing Deleted and Added entries with similar content.
detect_renames_with_policy
Like detect_renames, but honors index.threads / --threads via thread_policy.
diff_commits
Diff the trees recorded at two commits (base is the old side, tip the new side).
diff_commits_with_renames
Diff the trees at two commits and pair deleted/added paths as renames when similar enough.
diff_commits_with_renames_and_policy
Like diff_commits_with_renames, but honors index.threads / embedder thread policy.
diff_index_to_tree
Compare the index against a tree (usually HEAD’s tree).
diff_index_to_tree_with_renames
Diff the index against a tree and pair deleted/added paths as renames when similar enough.
diff_index_to_worktree
Compare the index against the working tree.
diff_index_to_worktree_for_staging
Like diff_index_to_worktree_with_options, but loads config from repository_git_dir (the main repository for linked worktrees) and persists each hashed worktree blob into odb so staging can update the index without re-reading file contents. Symlinks store their target bytes. With DiffIndexToWorktreeOptions::hash_blobs_without_write, returns the same blob IDs without writing objects, for staging previews.
diff_index_to_worktree_with_options
Compare tracked index entries with the worktree, using link-target bytes for symlinks.
diff_index_to_worktree_with_renames
Diff the index against the working tree and pair deleted/added paths as renames when similar.
diff_paths
Diff two filesystem paths (files, directories, or one of each).
diff_slice_ops_compacted
Line-diff ops for string slices after Git xdl_change_compact (and optional indent heuristic).
diff_tree_path_change_count
Count path-level differences between two trees without building a DiffEntry list.
diff_tree_to_worktree
Compare a tree against the working tree.
diff_tree_to_worktree_with_git_dir
Like diff_tree_to_worktree, but loads config from repository_git_dir (linked worktrees / gitfiles).
diff_tree_to_worktree_with_git_dir_and_rules
Like diff_tree_to_worktree_with_git_dir, with optional shared crate::worktree_rules::WorktreeRules.
diff_tree_to_worktree_with_git_dir_and_rules_extras
Like diff_tree_to_worktree_with_git_dir_and_rules, with worktree access policy for the slow path.
diff_trees
Compare two trees and return the list of changed entries.
diff_trees_show_tree_entries
Like diff_trees, but emit entries for tree objects themselves in addition to their recursive contents (Git’s diff-tree -t behavior).
diff_trees_with_renames
Diff two trees and pair deleted/added paths as renames when content is similar enough.
diff_trees_with_renames_and_policy
Like diff_trees_with_renames, but honors index.threads / embedder thread policy.
diff_trees_with_renames_and_policy_result
Like diff_trees_with_renames_and_policy, but also returns rename-limit skip metadata.
diffcore_count_changes
Approximate copied vs added material between two blobs (Git diffcore_count_changes).
empty_blob_oid
Return the ObjectId for the empty blob object.
entry_is_racy
Whether an index entry’s cached mtime is at or after the on-disk index file’s mtime.
entry_is_racy_with_policy
Like entry_is_racy, honoring core.usenanosec for sub-second racy detection.
flatten_tree_entries
Depth-first list of (path, mode, oid) blob entries in a tree (for copy detection).
for_each_tree_diff_structured
Visit structured tree diffs in path order without retaining every file’s hunks at once.
format_mode
Format a numeric mode as a zero-padded octal string.
format_raw
Format a diff entry in Git’s raw diff format.
format_raw_abbrev
Format a diff entry with abbreviated OIDs.
hash_worktree_file
Hash normalized worktree bytes for a path (does not write to the object database).
head_path_states
Paths present in HEAD’s tree with mode and blob/commit OID (for status porcelain v2).
hunk_diff_bundle
Load unstaged diffs and the staged peer hunks on the same paths.
indent_heuristic_from_config
diff.indentHeuristic from config (Git defaults to true when unset).
index_mtime_for_diff
Effective index-file mtime for racy-git checks.
line_change_counts
Count insertions and deletions between two text sides using DiffOptions’s algorithm.
line_diff_unified_hunk_body
Unified hunk bodies (@@ …) for two text sides using DiffOptions.
load_object_changes
Load both sides of each entry from the object database.
load_odb_blob_side_for_diff
Load ODB blob bytes for diffing, skipping inflation when over core.bigFileThreshold.
load_worktree_side_for_diff
Load worktree bytes for diffing, optionally skipping reads above core.bigFileThreshold.
materialize_worktree_blob
Read, normalize (CRLF/attributes), and store a worktree blob once.
mode_from_metadata
Derive a Git file mode from filesystem metadata.
name_status_line
Git --name-status letter for a diff entry (uppercase status + rename score suffix).
normalize_ignore_space_change
Normalise text like Git’s -b / --ignore-space-change: on each line, collapse runs of whitespace to a single ASCII space and trim trailing spaces.
normalize_ignore_space_change_line
Normalise one line like Git’s -b / --ignore-space-change (ASCII ws only).
parse_diff_rename_score_token
Parse a single Git parse_rename_score token (50, 50%, decimal forms) into internal 0–GIT_DIFF_MAX_SCORE units.
parse_diff_rename_threshold_percent
Parse -M / --find-renames threshold into Git’s 0–100 similarity percent.
postprocess_diff_entries
Apply break-rewrite, rename, and copy detection to a flat tree or index diff.
read_submodule_head_for_checkout
Read the HEAD commit OID from a submodule checkout directory.
read_submodule_head_oid
Read the HEAD commit OID from a submodule working tree directory.
read_worktree_bytes_for_mode
Read worktree content for diffing, honoring Git tree modes.
read_worktree_side_bytes_for_diff
Read worktree file bytes in Git (repository) form for line diffs against index or tree blobs.
refresh_index_stat_content_verified
Refresh cached stat data for stage-0 file/symlink entries whose worktree content still matches the recorded OID but whose on-disk stat went stale.
refresh_index_stat_content_verified_with_rules
Like refresh_index_stat_content_verified, resolving attributes and conversion through a shared crate::worktree_rules::WorktreeRules when one is supplied (its config snapshot then takes precedence over config).
rename_similarity_score
Compute rename/copy similarity percentage (0–100) between two byte slices.
renames_from_config
diff.renames: false disables; true or copy modes use default similarity.
resolve_commit_diff_pathspecs
Normalize pathspecs for a commit or range diff to repository-relative form.
resolve_diff_arguments
Parse grit diff flags and positionals into a DiffTarget and pathspecs.
resolve_diff_request
Decide what grit diff compares and which paths it is limited to.
resolve_indent_heuristic
Resolve indent heuristic: --no-indent-heuristic and --indent-heuristic override config.
rewrite_dissimilarity_index_percent
Percentage shown in dissimilarity index N% for a rewrite (similarity_index in Git’s diff.c).
rewrite_merge_score
Git merge_score from diffcore-break.c when a pair is considered broken: how much of the source blob was removed (0–DIFF_MAX_SCORE scale). Used for dissimilarity index metadata.
should_break_rewrite_pair
Whether an in-place blob edit should be split into delete+create for rename/copy (should_break in diffcore-break.c). break_score is on the internal 0–GIT_DIFF_MAX_SCORE scale (default DIFF_DEFAULT_BREAK_SCORE).
smudge_racily_clean_entries
Clear racily-clean cache lines on entries whose blob no longer matches the worktree.
sort_entries_by_path
Stable-sort diff entries by DiffEntry::path in raw byte order, Git’s output order for diff lists (non-UTF-8 paths compare by their decoded bytes).
stat_matches
Whether worktree metadata matches cached index stat data (Git ie_match_stat / match_stat_data).
stat_matches_with_policy
Like stat_matches, honoring core.trustctime, core.checkstat, and core.usenanosec.
status_apply_rename_copy_detection
Apply Git-style rename and optional copy detection for index↔worktree diffs.
submodule_commit_subject_line
First line of a commit’s message for git diff --submodule=log output.
submodule_embedded_git_dir
Resolve the embedded git directory for a submodule work tree (sub_dir/.git).
submodule_head_object_broken
True when a populated submodule checkout is broken: its HEAD resolves to a commit OID, but that commit object cannot be read from the submodule’s own object database.
submodule_porcelain_flags
Inspect a checked-out submodule at rel_path (relative to super_worktree) and return flags used for git status --porcelain=v2 submodule tokens.
text_sides_differ
Whether two text sides differ under whitespace options in opts.
tree_diff_contents_parallel
Load old/new blob bytes for each entry, using a worker pool when thresholds allow.
tree_diff_stat_parallel
Per-file line counts for stat modes (loads blobs, no hunk allocation).
tree_diff_structured_entry
Load sides and compute a structured line diff for one tree diff entry.
tree_diff_structured_parallel
Load sides and compute structured line diffs for each entry in parallel.
tree_oid_of_commit
Return the tree OID stored in a commit object.
tree_oid_of_commit_in_repo
Like tree_oid_of_commit, but uses the repository commit-graph cache when available.
unified_diff
Generate a unified diff patch for two blobs.
unified_diff_histogram_hunks_only
Unified diff hunks for Git’s histogram algorithm (no --- / +++ lines).
unified_diff_histogram_ignore_with_prefix_and_funcname
Full unified diff (--- / +++ / hunks) using Git’s histogram algorithm, applying --ignore-blank-lines / -I change-record suppression (histogram_unified_body_ignore_fc) and then attaching function-name hunk headers like unified_diff_histogram_with_prefix_and_funcname_indent.
unified_diff_with_prefix
Same as unified_diff but with configurable source/destination prefixes.
unified_diff_with_prefix_and_funcname
Same as unified_diff_with_prefix with optional custom hunk-header function-name matching.
unified_diff_with_prefix_and_funcname_and_algorithm
Same as unified_diff_with_prefix_and_funcname but allows callers to choose the line diff algorithm used for hunk generation.
worktree_differs_from_index_entry
Quick stat check: does the index entry’s cached stat data match the file? Returns true when the file at ie’s path differs from the index entry (mode or blob).
write_commit_header_and_message
Write commit header (author, date, indented message) after the commit line.
write_commit_log_patch
Write one commit in git log -p --no-color --format=%H shape (no patch for merges).
write_commits_log_patch
Like write_commit_log_patch for many commits (avoids re-reading parent commits).
write_diff_entry_log_patch
Write the diff --git header and unified body for one DiffEntry.
write_patch
Write git diff --binary-style patches for tree diff entries (for git apply).
write_patch_resolved
Write git diff --binary-compatible patch text for files whose sides may live in memory, the object database, or the work tree (index and work-tree diffs).
write_patch_structured
Write patch text from precomputed TreeDiffStructured rows.
write_paths_patch
Write git diff --no-index --binary-style patch bytes for two filesystem paths.
write_unified_diff_with_prefix_and_funcname_and_algorithm
Same as unified_diff_with_prefix_and_funcname_and_algorithm, streaming to out.
zero_oid
Return the zero ObjectId.

Type Aliases§

IndexPathSkipPredicate
Predicate over stored index path bytes for DiffIndexToWorktreeOptions::skip_index_path.