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).
diffstat
diffstat 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).
DiffArguments
Resolved diff mode and normalized pathspecs.
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.
DiffTotals
Summary across all files in a stat-style diff.
FileDiff
One changed file with structured hunks and metadata.
HunkDiffBundle
Staged and unstaged file diffs for hunk id assignment (one staged scan per call).
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).
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.
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_DEFAULT_MERGE_SCORE_AFTER_BREAK
Default merge threshold after a break (DEFAULT_MERGE_SCORE in diffcore.h): pairs broken for rename/copy but not consumed are merged back when deletion-weight is below this (60% by default).
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).
ZERO_OID
The zero (null) object ID used for “no object” in diff output.

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.
append_untracked_worktree_added_for_rename_detection
Add DiffStatus::Added entries for untracked worktree files so rename detection can pair plain filesystem moves (index still lists the old path, new path only on disk).
apply_diff_filter
Drop entries that do not match filter (Git --diff-filter, after rename detection).
apply_orderfile_entries
Reorder diff entries by a -O<orderfile> (diff.orderFile): entries are sorted by the index of the first orderfile glob pattern that matches their path; unmatched entries sort last (stable).
apply_rename_detection_to_diff_entries
Apply Git -M rename detection to a flat diff (index↔tree, tree↔tree, or index↔worktree).
apply_rotate_skip_entries
Reorder diff entries for git diff --rotate-to / --skip-to (changed paths only).
apply_rotate_skip_log_entries
git log rotate/skip: reorder using the commit tree path order (all blobs), then keep only paths present in entries — matches Git’s diff --rotate-to with history walks.
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.
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
Count insertions and deletions between two strings.
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.
diff_index_to_worktree_with_options
Errors
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_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.
diffcore_count_changes
Approximate copied vs added material between two blobs (Git diffcore_count_changes).
drop_unused_synthetic_rename_candidates
Drop synthetic untracked rename candidates that rename detection did not pair.
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.
format_rename_path
Format a rename pair using Git’s compact path format.
format_stat_line
Generate diff stat output (file name + insertions/deletions).
format_stat_line_width
Format one --stat line with explicit path and count column widths.
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, staged peer hunks, and staged-side file rows in one pass.
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.
map_new_to_old_lines_compacted
Map each line in new_joined to its origin in old_joined after Git-style compaction (for blame).
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).
orderfile_pattern_matches
Check if an orderfile pattern matches a path (matches the basename or the full path). Supports basic glob patterns: * matches any sequence, ? matches one char.
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.
parse_indent_heuristic_cli_flags
Parse --indent-heuristic / --no-indent-heuristic from a plumbing argv slice (last occurrence wins).
path_checkout_skip_blob_write_when_up_to_date
Whether path-only checkout can skip writing a blob because the worktree is up to date.
postprocess_diff_entries
Apply break-rewrite, rename, and copy detection to a flat tree or index diff.
read_orderfile_patterns
Read non-empty, non-comment glob patterns (one per line) from a -O<orderfile> file.
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_diff_arguments
Parse grit diff flags and positionals into a DiffTarget and pathspecs.
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_for_stat
Whether this modified blob pair should use Git’s “complete rewrite” diffstat path when --break-rewrites is in effect (should_break in diffcore-break.c).
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.
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 exactly like unified_diff_histogram_with_prefix_and_funcname.
unified_diff_histogram_with_prefix_and_funcname
Full unified diff (--- / +++ / hunks) using Git’s histogram algorithm.
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.
word_diff_ops_imara
Diff two token streams with a Git-compatible implementation of the xdiff Myers engine and return the result as similar::DiffOps. Used by the word-diff machinery, where matching Git’s exact record selection and tie-breaking matters: imara-diff/similar pick different — but equally minimal — alignments for streams with many repeated tokens (e.g. the bibtex driver’s {/}/,), mismatching Git’s reference output.
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.