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§
- Commit
Files Many Input - One commit’s identity for
Diff::commit_files_many_work, avoiding a second ODB read. - Commit
Files Many Options - Options for
Diff::commit_files_many. - Commit
Files Result - One commit’s diff output in
Diff::commit_files_many(same order as input oids). - Diff
Arguments - Resolved diff mode and normalized pathspecs.
- Diff
Entry - A single diff entry representing one changed path.
- Diff
Files Output - Output of
build_file_diffs. - Diff
Filter - Typed include/exclude set for
DiffStatususing Git’s letter syntax. - Diff
Index ToWorktree Options - Additional inputs for
diff_index_to_worktree_with_options. - Diff
Options - Line-diff options shared by structured output, log patches, and benchmarks.
- Diff
Postprocess Options - Options for Git-style rename, copy, and break-rewrite post-processing on tree diffs.
- Diff
Postprocess Worktree - Index and git directory used to read canonical (clean) worktree bytes during break-rewrite post-processing on tree↔worktree diffs.
- Diff
Totals - Summary across all files in a stat-style diff.
- File
Diff - One changed file with structured hunks and metadata.
- Hunk
Diff Bundle - Staged and unstaged file diffs for hunk id assignment (one staged scan per call).
- Line
Stat - Line insertion/deletion counts for one file (
--numstat). - Listed
File Diff - One changed file with optional patch body or line counts.
- LogPatch
Options - Options for
write_commit_log_patch. - Patch
Resolved Side - One file for
write_patch_resolved: diff metadata plus where each side’s content is. - Patch
Text Options - Options for
write_patch(git diff --binary-compatible output forgit apply). - Submodule
Porcelain Flags - Submodule dirty bits aligned with Git’s
DIRTY_SUBMODULE_*/ porcelain v2S???token. - Tree
Diff Content - One tree diff entry with both sides loaded for line-level diffing.
- Tree
Diff Structured - Tree diff entry with structured line hunks ready for CLI rendering.
- Unknown
Diff Algorithm - Unknown value for
DiffAlgorithm’sFromStrimplementation. - Whitespace
Mode - Whitespace handling for line diffs (
super::DiffOptions::whitespace). - Worktree
AddRefresh Params - Inputs for
classify_worktree_entry_for_add.
Enums§
- Diff
Algorithm - Line diff algorithm names matching Git’s
diff.algorithmand--diff-algorithm. - Diff
Detail - How much content to compute for each changed file.
- Diff
Merges - How to diff a merge commit’s tree against its parents.
- Diff
Status - The kind of change between two sides of a diff.
- Diff
Target - What to compare when producing a structured file diff list.
- Invalid
Diff Filter - Unknown or unsupported
--diff-filterletter. - LogPatch
Binary Format - Binary file encoding inside a log/show patch (
git log -pvsgit diff --binary). - LogPatch
Commit Header - How much commit metadata precedes each patch in
write_commit_log_patch. - NoIndex
Error - Failure modes specific to
diff_paths. - Patch
Side - Where
write_patch_resolvedtakes the content of one side of a file. - Rename
Detection - Rename detection policy for tree diffs.
- Resolve
Diff Arguments Error - Invalid
grit diffargument combinations or revision parsing failures. - Worktree
AddRefresh - 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_SCOREindiffcore.h), internal 0–GIT_DIFF_MAX_SCOREscale. - GIT_
DIFF_ DEFAULT_ MERGE_ SCORE_ AFTER_ BREAK - Default merge threshold after a break (
DEFAULT_MERGE_SCOREindiffcore.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_SCOREindiffcore.h). - RENAME_
DETECTION_ DISABLED - u32 rename APIs: thresholds
0–100run detection at that Git-Mpercent;RENAME_DETECTION_DISABLED(101) and above skip detection (legacy postprocess and--no-renamesplumbing). - 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 fileafter-/+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::Addedentries 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
-Mrename 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 logrotate/skip: reorder using the commit tree path order (all blobs), then keep only paths present inentries— matches Git’sdiff --rotate-towith history walks.- build_
file_ diffs - Fill per-file diff bodies for tree/index diff entries.
- build_
file_ diffs_ streaming - Build patch
FileDiffrows 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
CombinedStructuredTextDiffas 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’scount_lines()indiff.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 honorsindex.threads/--threadsviathread_policy. - diff_
commits - Diff the trees recorded at two commits (
baseis the old side,tipthe 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 honorsindex.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 fromrepository_git_dir(the main repository for linked worktrees) and persists each hashed worktree blob intoodbso 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
DiffEntrylist. - 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 fromrepository_git_dir(linked worktrees / gitfiles). - diff_
tree_ to_ worktree_ with_ git_ dir_ and_ rules - Like
diff_tree_to_worktree_with_git_dir, with optional sharedcrate::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’sdiff-tree -tbehavior). - 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 honorsindex.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, honoringcore.usenanosecfor 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
--statline 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.indentHeuristicfrom 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 usingDiffOptions. - map_
new_ to_ old_ lines_ compacted - Map each line in
new_joinedto its origin inold_joinedafter 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-statusletter 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_scoretoken (50,50%, decimal forms) into internal 0–GIT_DIFF_MAX_SCOREunits. - parse_
diff_ rename_ threshold_ percent - Parse
-M/--find-renamesthreshold into Git’s 0–100 similarity percent. - parse_
indent_ heuristic_ cli_ flags - Parse
--indent-heuristic/--no-indent-heuristicfrom 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 sharedcrate::worktree_rules::WorktreeRuleswhen one is supplied (its config snapshot then takes precedence overconfig). - rename_
similarity_ score - Compute rename/copy similarity percentage (0–100) between two byte slices.
- renames_
from_ config diff.renames:falsedisables;trueor copy modes use default similarity.- resolve_
diff_ arguments - Parse
grit diffflags and positionals into aDiffTargetand pathspecs. - resolve_
indent_ heuristic - Resolve indent heuristic:
--no-indent-heuristicand--indent-heuristicoverride config. - rewrite_
dissimilarity_ index_ percent - Percentage shown in
dissimilarity index N%for a rewrite (similarity_indexin Git’s diff.c). - rewrite_
merge_ score - Git
merge_scorefromdiffcore-break.cwhen a pair is considered broken: how much of the source blob was removed (0–DIFF_MAX_SCOREscale). Used fordissimilarity indexmetadata. - should_
break_ rewrite_ for_ stat - Whether this modified blob pair should use Git’s “complete rewrite” diffstat path when
--break-rewritesis in effect (should_breakindiffcore-break.c). - should_
break_ rewrite_ pair - Whether an in-place blob edit should be split into delete+create for rename/copy (
should_breakindiffcore-break.c).break_scoreis on the internal 0–GIT_DIFF_MAX_SCOREscale (defaultDIFF_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, honoringcore.trustctime,core.checkstat, andcore.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=logoutput. - 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
HEADresolves 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 tosuper_worktree) and return flags used forgit status --porcelain=v2submodule 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/-Ichange-record suppression (histogram_unified_body_ignore_fc) and then attaching function-name hunk headers exactly likeunified_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_diffbut with configurable source/destination prefixes. - unified_
diff_ with_ prefix_ and_ funcname - Same as
unified_diff_with_prefixwith optional custom hunk-header function-name matching. - unified_
diff_ with_ prefix_ and_ funcname_ and_ algorithm - Same as
unified_diff_with_prefix_and_funcnamebut 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/similarpick different — but equally minimal — alignments for streams with many repeated tokens (e.g. thebibtexdriver’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
commitline. - write_
commit_ log_ patch - Write one commit in
git log -p --no-color --format=%Hshape (no patch for merges). - write_
commits_ log_ patch - Like
write_commit_log_patchfor many commits (avoids re-reading parent commits). - write_
diff_ entry_ log_ patch - Write the
diff --githeader and unified body for oneDiffEntry. - write_
patch - Write
git diff --binary-style patches for tree diff entries (forgit 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
TreeDiffStructuredrows. - 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 toout. - zero_
oid - Return the zero ObjectId.