pub struct Diff<'repo> { /* private fields */ }Expand description
Compare trees, the index, and the working tree for one repository.
Obtain it from Repository::diff. The metadata diffs (Self::tree_to_tree,
Self::commits, Self::index_to_tree, Self::index_to_worktree,
Self::tree_to_worktree) list changed paths without loading contents and take one
TreeDiffOptions; the content methods (Self::files_for_entries, Self::stat,
Self::structured, Self::for_each_structured, …) turn those entries into hunks and
line counts under a DiffOptions. Configuration is read from the repository.
Implementations§
Source§impl Diff<'_>
impl Diff<'_>
Sourcepub fn commit_files_many(
&self,
oids: &[ObjectId],
pathspec: &Pathspec,
opts: CommitFilesManyOptions,
config: &ConfigSet,
thread_policy: &ThreadPolicy,
) -> Result<Vec<CommitFilesResult>>
pub fn commit_files_many( &self, oids: &[ObjectId], pathspec: &Pathspec, opts: CommitFilesManyOptions, config: &ConfigSet, thread_policy: &ThreadPolicy, ) -> Result<Vec<CommitFilesResult>>
Build per-commit file diffs for a slice of commit oids, preserving input order.
Parent trees are resolved once and reused across consecutive commits (same as
super::write_commits_log_patch). When oids are newest-first and history is
linear, each commit’s first parent is the next oid and its tree is reused without
an extra read. Work runs in parallel when ThreadPolicy allows and the batch is
large enough to amortize pool startup.
§Errors
Propagates object read, tree diff, and parallel pool errors.
Sourcepub fn commit_line_totals(
&self,
oids: &[ObjectId],
pathspec: &Pathspec,
diff_options: DiffOptions,
config: &ConfigSet,
thread_policy: &ThreadPolicy,
) -> Result<Vec<Option<DiffTotals>>>
pub fn commit_line_totals( &self, oids: &[ObjectId], pathspec: &Pathspec, diff_options: DiffOptions, config: &ConfigSet, thread_policy: &ThreadPolicy, ) -> Result<Vec<Option<DiffTotals>>>
Lines each commit added and removed against its first parent, in input order.
This is the per-commit summary of git log --shortstat: a root commit is compared with
the empty tree, and a merge (two or more parents) is not diffed at all and gets None.
Commits that change no lines (or only binary files) get Some totals with zero
insertions and deletions, so callers decide whether to show them.
§Parameters
oids: commits to summarize; newest-first linear history reuses each parent tree.pathspecs: resolved pathspecs limiting the counted paths (empty counts every path).diff_options: rename and line-diff settings, usuallyDiffOptions::from_config.config: repository configuration for attributes and parallelism.thread_policy: worker limits for the batch.
§Errors
Propagates object read (including a non-commit oid), tree diff, and parallel pool
errors.
Sourcepub fn commit_files_many_work(
&self,
inputs: &[CommitFilesManyInput],
pathspec: &Pathspec,
opts: CommitFilesManyOptions,
config: &ConfigSet,
thread_policy: &ThreadPolicy,
) -> Result<Vec<CommitFilesResult>>
pub fn commit_files_many_work( &self, inputs: &[CommitFilesManyInput], pathspec: &Pathspec, opts: CommitFilesManyOptions, config: &ConfigSet, thread_policy: &ThreadPolicy, ) -> Result<Vec<CommitFilesResult>>
Like Self::commit_files_many when commit trees and parents are already loaded.
§Errors
Propagates object read, tree diff, and parallel pool errors.
Source§impl<'repo> Diff<'repo>
impl<'repo> Diff<'repo>
Sourcepub fn new(repo: &'repo Repository) -> Self
pub fn new(repo: &'repo Repository) -> Self
Bind diff helpers to repo.
Sourcepub fn repository(&self) -> &'repo Repository
pub fn repository(&self) -> &'repo Repository
Underlying repository.
Sourcepub fn tree_to_tree(
&self,
old_tree: Option<&ObjectId>,
new_tree: Option<&ObjectId>,
options: &TreeDiffOptions,
) -> Result<DiffEntriesResult>
pub fn tree_to_tree( &self, old_tree: Option<&ObjectId>, new_tree: Option<&ObjectId>, options: &TreeDiffOptions, ) -> Result<DiffEntriesResult>
Diff two tree oids (either side may be None for an empty tree).
Reads tree metadata without loading blobs and skips identical subtree ids; with a
pathspec, directories it cannot reach are not read. Rename, copy and break pairing
follow options (none by default). The walk retains active directory frames alongside
the ODB’s bounded tree cache; the result owns metadata for every changed path.
§Parameters
old_tree- old side, orNonefor the empty tree.new_tree- new side, orNonefor the empty tree.options- pathspec, pairing,prefixandshow_tree_entries.
§Errors
Propagates ODB read, tree walk, pathspec and rename detection errors.
§Examples
use grit_lib::diff::{DiffStatus, RenameDetection, TreeDiffOptions};
use grit_lib::objects::{serialize_tree, ObjectKind, TreeEntry};
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
let blob = repo.odb().write(ObjectKind::Blob, b"one\ntwo\nthree\n")?;
let tree = |name: &str| {
let entry = TreeEntry {
mode: 0o100644,
name: name.as_bytes().to_vec(),
oid: blob,
};
repo.odb().write(ObjectKind::Tree, &serialize_tree(&[entry]))
};
let (old, new) = (tree("a.txt")?, tree("b.txt")?);
let plain = repo.diff().tree_to_tree(Some(&old), Some(&new), &TreeDiffOptions::default())?;
assert_eq!(plain.entries.len(), 2); // a.txt deleted, b.txt added
let options = TreeDiffOptions::default().with_renames(RenameDetection::Similarity(50));
let renamed = repo.diff().tree_to_tree(Some(&old), Some(&new), &options)?;
assert_eq!(renamed.entries.len(), 1);
assert_eq!(renamed.entries[0].status, DiffStatus::Renamed);See also the library guide on diffing.
Sourcepub fn commits(
&self,
base: &ObjectId,
tip: &ObjectId,
options: &TreeDiffOptions,
) -> Result<DiffEntriesResult>
pub fn commits( &self, base: &ObjectId, tip: &ObjectId, options: &TreeDiffOptions, ) -> Result<DiffEntriesResult>
Diff the trees recorded at two commits (base is the old side, tip the new side).
Same as Self::tree_to_tree on the commits’ trees.
§Errors
Returns RefError::Invalid when either id is not a
commit, plus the errors of Self::tree_to_tree.
Sourcepub fn index_to_tree(
&self,
index: &Index,
tree: Option<&ObjectId>,
options: &TreeDiffOptions,
) -> Result<DiffEntriesResult>
pub fn index_to_tree( &self, index: &Index, tree: Option<&ObjectId>, options: &TreeDiffOptions, ) -> Result<DiffEntriesResult>
Diff the index against a tree (typically HEAD’s tree, Git diff --cached).
Uses the index’s cache tree to skip unchanged directories when it is valid.
SubmoduleIgnoreMode::All omits gitlink paths.
§Parameters
index- the index to compare (the new side).tree- the old side, orNonefor the empty tree.options- pathspec, pairing and submodule policy.
§Errors
Propagates ODB, index diff, pathspec and rename detection errors.
Sourcepub fn index_to_worktree(
&self,
index: &mut Index,
options: &TreeDiffOptions,
) -> Result<DiffEntriesResult>
pub fn index_to_worktree( &self, index: &mut Index, options: &TreeDiffOptions, ) -> Result<DiffEntriesResult>
Diff the working tree against the index (Git diff-files).
Entries whose stat data matches the index are not read; a changed file’s work-tree
side carries a null new_oid unless its content had to be hashed to prove it changed.
With a pathspec only the paths it selects are scanned. Submodule checkouts are
compared per TreeDiffOptions::submodules. With
TreeDiffOptions::refresh_index_stat unchanged entries adopt fresh stat data in
index; nothing is written to disk.
§Errors
Returns RepositoryError::RequiresWorkTree in a bare repository, and work-tree I/O,
ODB, pathspec and rename detection errors.
Sourcepub fn tree_to_worktree(
&self,
tree: Option<&ObjectId>,
index: &Index,
options: &TreeDiffOptions,
) -> Result<DiffEntriesResult>
pub fn tree_to_worktree( &self, tree: Option<&ObjectId>, index: &Index, options: &TreeDiffOptions, ) -> Result<DiffEntriesResult>
Diff the working tree against a tree, through index (Git diff <tree>).
When the index’s cache tree matches tree, this is the cheaper index-to-work-tree
scan; otherwise the tree is walked against the work tree. Work-tree bytes go through
the repository’s attributes and clean filters. Break-rewrite pairing fills the
work-tree side’s blob id like Git. SubmoduleIgnoreMode::All omits gitlink paths;
the other modes compare a submodule’s checked-out commit.
§Parameters
tree- the old side, orNonefor the empty tree.index- the index tracking the work tree.options- pathspec, pairing and submodule policy.
§Errors
Returns RepositoryError::RequiresWorkTree in a bare repository, and work-tree I/O,
ODB, pathspec and rename detection errors.
Sourcepub fn detect_renames(
&self,
entries: Vec<DiffEntry>,
source_tree: Option<&ObjectId>,
options: &TreeDiffOptions,
) -> Result<DiffEntriesResult>
pub fn detect_renames( &self, entries: Vec<DiffEntry>, source_tree: Option<&ObjectId>, options: &TreeDiffOptions, ) -> Result<DiffEntriesResult>
Apply the rename, copy and break pairing of options to entries listed elsewhere.
Old sides are read from the object database; a new side with a null new_oid is read
from the work tree. The pathspec, prefix and submodule fields of options are not used.
§Parameters
entries- changed paths to pair, e.g. a filteredSelf::tree_to_treeresult.source_tree- withCopyDetection::FindHarder, every blob in this tree is a copy source as well;Nonelimits sources toentries.options- rename, copy and break pairing and thread limits.
§Errors
Propagates object and work-tree reads while scoring pairs.
Sourcepub fn uncommitted(&self) -> Result<UncommittedDiff<'repo>>
pub fn uncommitted(&self) -> Result<UncommittedDiff<'repo>>
Staged, unstaged, and working-tree diffs over the repository’s on-disk index.
§Errors
Returns index read errors.
Sourcepub fn entries(
&self,
target: &DiffTarget,
pathspec: &Pathspec,
options: &DiffOptions,
) -> Result<DiffEntriesResult>
pub fn entries( &self, target: &DiffTarget, pathspec: &Pathspec, options: &DiffOptions, ) -> Result<DiffEntriesResult>
Changed paths for target, limited to pathspecs and to the statuses in
options.filter (--diff-filter), sorted by path. No contents are loaded.
Commit and tree targets diff stored trees without reading the index. Targets that read
the index or working tree load it once here; when their contents are needed next, call
UncommittedDiff::entries on Self::uncommitted instead and load them with
UncommittedDiff::load_worktree_changes or Self::object_changes on the same
handle.
§Parameters
target- what to compare, e.g. fromSelf::resolve_request.pathspec- repository-relative pathspecs; an entire-tree pathspec means every path.options- onlyrenamesandfilterare used.
§Errors
Returns object read, rename detection, and pathspec errors, plus
RepositoryError::RequiresWorkTree for a working-tree target in a bare repository.
Sourcepub fn files(
&self,
target: &DiffTarget,
pathspec: &Pathspec,
opts: &DiffOptions,
) -> Result<Vec<FileDiff>>
pub fn files( &self, target: &DiffTarget, pathspec: &Pathspec, opts: &DiffOptions, ) -> Result<Vec<FileDiff>>
Structured per-file diffs for target, honoring pathspecs and line-diff opts.
§Errors
Propagates index, ODB, and worktree diff failures.
Sourcepub fn files_for_entries(
&self,
entries: Vec<DiffEntry>,
detail: DiffDetail,
options: &DiffOptions,
) -> Result<DiffFilesOutput>
pub fn files_for_entries( &self, entries: Vec<DiffEntry>, detail: DiffDetail, options: &DiffOptions, ) -> Result<DiffFilesOutput>
Per-file diffs at detail for entries from a metadata diff.
Applies DiffOptions::renames to the entries first (Git’s default -M50); pass
RenameDetection::Off when the entries are already
paired. DiffDetail::NameOnly and DiffDetail::NameStatus load no contents;
DiffDetail::Stat counts lines and DiffDetail::Patch builds hunks, in parallel
when the repository’s thread policy allows.
§Errors
Propagates object database and parallel diff errors.
Sourcepub fn for_each_file(
&self,
entries: Vec<DiffEntry>,
options: &DiffOptions,
emit: impl FnMut(ListedFileDiff) -> Result<()>,
) -> Result<()>
pub fn for_each_file( &self, entries: Vec<DiffEntry>, options: &DiffOptions, emit: impl FnMut(ListedFileDiff) -> Result<()>, ) -> Result<()>
Patch rows for entries one file at a time, without retaining every hunk list.
Like Self::files_for_entries at DiffDetail::Patch, but emit receives each
file in path order and peak memory stays near one file’s diff.
§Errors
Propagates object database, parallel diff and emit errors.
Sourcepub fn stat(
&self,
entries: Vec<DiffEntry>,
options: &DiffOptions,
) -> Result<DiffStat>
pub fn stat( &self, entries: Vec<DiffEntry>, options: &DiffOptions, ) -> Result<DiffStat>
Diffstat (per-file insertions and deletions) for entries.
Same rename handling as Self::files_for_entries at DiffDetail::Stat.
§Errors
Propagates object database and parallel diff errors.
Sourcepub fn structured(
&self,
entries: Vec<DiffEntry>,
options: &DiffOptions,
) -> Result<Vec<TreeDiffStructured>>
pub fn structured( &self, entries: Vec<DiffEntry>, options: &DiffOptions, ) -> Result<Vec<TreeDiffStructured>>
Structured hunks for every entry, in input order, computed in parallel when the repository’s thread policy allows. Entries are used as given (no rename pairing).
§Errors
Propagates object database and parallel diff errors.
Sourcepub fn for_each_structured(
&self,
entries: &[DiffEntry],
options: &DiffOptions,
visit: impl FnMut(TreeDiffStructured) -> Result<()>,
) -> Result<()>
pub fn for_each_structured( &self, entries: &[DiffEntry], options: &DiffOptions, visit: impl FnMut(TreeDiffStructured) -> Result<()>, ) -> Result<()>
Like Self::structured, but hands each file to visit in input order instead of
collecting them, so only a bounded window of results is held at once.
§Errors
Propagates object database, parallel diff and visit errors.
Sourcepub fn commit_files(
&self,
commit: &ObjectId,
merges: DiffMerges,
detail: DiffDetail,
options: &DiffOptions,
pathspec: &Pathspec,
) -> Result<DiffFilesOutput>
pub fn commit_files( &self, commit: &ObjectId, merges: DiffMerges, detail: DiffDetail, options: &DiffOptions, pathspec: &Pathspec, ) -> Result<DiffFilesOutput>
Per-file diffs for one commit against its parents (Git show / log -p for a commit).
A root commit is compared with the empty tree. A merge (two or more effective parents,
after grafts and shallow boundaries) is diffed per merges.
§Parameters
commit- the commit to show.merges- how merge commits are diffed.detail- how much to compute per changed file.options- line-diff and rename settings.pathspec- paths to keep; an entire-tree pathspec keeps every path.
§Errors
Propagates object read, tree diff, pathspec and parallel diff errors.
Sourcepub fn object_changes(&self, entries: &[DiffEntry]) -> Result<Vec<FileChange>>
pub fn object_changes(&self, entries: &[DiffEntry]) -> Result<Vec<FileChange>>
Load old and new contents for entries that compare stored objects (trees, commits or the index against a tree), in parallel when the thread policy allows.
Work-tree entries need UncommittedDiff::load_worktree_changes instead.
§Errors
Propagates object read errors.
Sourcepub fn hunk_bundle(
&self,
pathspec: &Pathspec,
options: &DiffOptions,
) -> Result<HunkDiffBundle>
pub fn hunk_bundle( &self, pathspec: &Pathspec, options: &DiffOptions, ) -> Result<HunkDiffBundle>
Unstaged file diffs for pathspec plus the hunks other paths share with them, the
input for hunk-level staging by HunkId.
§Errors
Returns RepositoryError::RequiresWorkTree in a bare repository, and index, ODB and
work-tree diff errors.
Sourcepub fn resolve_request(
&self,
cwd_prefix: Option<&str>,
request: &DiffRequest,
) -> Result<DiffArguments>
pub fn resolve_request( &self, cwd_prefix: Option<&str>, request: &DiffRequest, ) -> Result<DiffArguments>
Turn a user’s diff request (staged/unstaged flags, revisions and paths) into a
DiffTarget and resolved pathspecs.
§Parameters
cwd_prefix- work-tree-relative directory the paths are relative to.request- what the user asked for.
§Errors
Returns DiffError::Arguments with a
ResolveDiffArgumentsError for conflicting flags, unknown or non-commit revisions,
bad pathspecs, and work-tree targets in a bare repository, plus revision errors such as
RevisionError::NoMergeBase for ranges.
Sourcepub fn resolve_pathspec(
&self,
cwd_prefix: Option<&str>,
raw_paths: &[String],
) -> Result<Pathspec>
pub fn resolve_pathspec( &self, cwd_prefix: Option<&str>, raw_paths: &[String], ) -> Result<Pathspec>
Resolve pathspecs that limit a commit diff (show, log -p), also in a bare
repository, where they are relative to the repository root.
§Errors
Returns DiffError::Arguments with a
ResolveDiffArgumentsError for pathspecs outside the repository or with invalid
magic.
Source§impl<'repo> Diff<'repo>
impl<'repo> Diff<'repo>
Sourcepub fn blame(&self, path: &str, options: &BlameOptions) -> Result<BlameResult>
pub fn blame(&self, path: &str, options: &BlameOptions) -> Result<BlameResult>
Attribute each line of a worktree path to a commit (blame).
§Errors
Propagates blame resolution, object read, and worktree failures documented on
[crate::blame::blame_file].
Sourcepub fn resolve_blame_line_range(
&self,
start: ObjectId,
path: &str,
spec: &str,
) -> Result<RangeInclusive<usize>, LineRangeError>
pub fn resolve_blame_line_range( &self, start: ObjectId, path: &str, spec: &str, ) -> Result<RangeInclusive<usize>, LineRangeError>
Resolve a Git-style -L range for blame on path at a fixed start commit.
Sourcepub fn resolve_blame_line_range_with_options(
&self,
path: &str,
spec: &str,
options: &BlameOptions,
) -> Result<RangeInclusive<usize>, LineRangeError>
pub fn resolve_blame_line_range_with_options( &self, path: &str, spec: &str, options: &BlameOptions, ) -> Result<RangeInclusive<usize>, LineRangeError>
Resolve a Git-style -L range using full crate::blame::BlameOptions.
Source§impl<'repo> Diff<'repo>
impl<'repo> Diff<'repo>
Sourcepub fn has_changes(
&self,
target: &DiffTarget,
pathspec: &Pathspec,
opts: &DiffOptions,
) -> Result<bool>
pub fn has_changes( &self, target: &DiffTarget, pathspec: &Pathspec, opts: &DiffOptions, ) -> Result<bool>
Whether the selected diff has any real changes, stopping at the first one.
Worktree targets honor the index stat cache and only hash blob content when needed.
When whitespace ignore flags are set on opts, content is compared under those rules;
a change that differs only in ignored whitespace returns false.
§Errors
Propagates repository, ODB, and diff errors.