Skip to main content

Diff

Struct Diff 

Source
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<'_>

Source

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.

Source

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, usually DiffOptions::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.

Source

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>

Source

pub fn new(repo: &'repo Repository) -> Self

Bind diff helpers to repo.

Source

pub fn repository(&self) -> &'repo Repository

Underlying repository.

Source

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, or None for the empty tree.
  • new_tree - new side, or None for the empty tree.
  • options - pathspec, pairing, prefix and show_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.

Source

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.

Source

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, or None for the empty tree.
  • options - pathspec, pairing and submodule policy.
§Errors

Propagates ODB, index diff, pathspec and rename detection errors.

Source

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.

Source

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, or None for 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.

Source

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 filtered Self::tree_to_tree result.
  • source_tree - with CopyDetection::FindHarder, every blob in this tree is a copy source as well; None limits sources to entries.
  • options - rename, copy and break pairing and thread limits.
§Errors

Propagates object and work-tree reads while scoring pairs.

Source

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.

Source

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. from Self::resolve_request.
  • pathspec - repository-relative pathspecs; an entire-tree pathspec means every path.
  • options - only renames and filter are used.
§Errors

Returns object read, rename detection, and pathspec errors, plus RepositoryError::RequiresWorkTree for a working-tree target in a bare repository.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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>

Source

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].

Source

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.

Source

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>

Source

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.

Trait Implementations§

Source§

impl<'repo> Clone for Diff<'repo>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'repo> Copy for Diff<'repo>

Source§

impl<'repo> Debug for Diff<'repo>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'repo> !RefUnwindSafe for Diff<'repo>

§

impl<'repo> !UnwindSafe for Diff<'repo>

§

impl<'repo> Forget for Diff<'repo>

§

impl<'repo> Freeze for Diff<'repo>

§

impl<'repo> Send for Diff<'repo>

§

impl<'repo> Sync for Diff<'repo>

§

impl<'repo> Unpin for Diff<'repo>

§

impl<'repo> UnsafeUnpin for Diff<'repo>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.