Skip to main content

Repository

Struct Repository 

Source
pub struct Repository { /* private fields */ }
Expand description

A handle to an open Git repository.

§Config and path caching

On open, Grit resolves the common git directory (Self::common_git_dir), loads the merged configuration cascade once, and keeps that snapshot for the lifetime of this handle. Hot paths (object reads, replace-ref checks, and similar) reuse the snapshot without re-statting config files on every access.

Refresh the snapshot when on-disk config may have changed:

§Examples

use grit_lib::prelude::RepositoryOptions;
use grit_lib::repo::{InitOptions, Repository};

let dir = tempfile::tempdir()?;
let repo = Repository::init(dir.path(), &InitOptions::default())?;
let reopened = Repository::open(
    repo.git_dir(),
    &RepositoryOptions::empty().with_work_tree(dir.path()),
)?;
assert_eq!(reopened.git_dir(), repo.git_dir());

Implementations§

Source§

impl Repository

Source

pub fn ignore_check( &self, paths: &[String], index: &Index, ) -> Result<Vec<IgnoreCheck>>

Check whether paths are ignored, reusing one IgnoreMatcher for the whole batch.

Tracked index entries are never reported as ignored. Each result includes verbose-style match metadata compatible with git check-ignore -v.

§Parameters
  • paths - repository-relative paths with / separators (as returned by normalize_repo_relative).
  • index - current index; tracked paths are treated as not ignored.
§Errors

Returns Error::Io when loading exclude files fails.

Source§

impl Repository

Source

pub fn write_commit_graph( &self, opts: &CommitGraphOptions, ) -> Result<CommitGraphWriteReport>

Write a reachable commit-graph file for this repository.

§Errors

See write_commit_graph.

Source

pub fn write_midx(&self, opts: &MidxOptions) -> Result<MidxWriteReport>

Write or refresh the multi-pack index for this repository’s pack directory.

§Errors

See write_midx.

Source§

impl Repository

Source

pub fn revision_label(&self, spec: &str) -> Result<Option<RevisionLabel>>

Classify spec as a short local branch or tag name for display.

Symbolic HEAD labels its local branch, including an unborn branch; detached HEAD has no label. Otherwise, short branch names take precedence over short tag names. Other inputs return None unless they themselves name a short branch or tag. This does not interpret revision expressions or fully qualified ref names; use Self::resolve to resolve a revision.

Uses this repository’s ref store, including injected backends. Annotated tags retain their raw metadata and message, without peeling the target or trimming whitespace. Ref lookup failures are treated as absent labels, so callers can resolve the revision independently.

§Errors

Returns an object-store error if a named tag’s object cannot be read, or Error::CorruptObject if an annotated tag cannot be parsed.

Source

pub fn resolve(&self, spec: &str) -> Result<ResolvedObject, ResolveError>

Resolve spec to an object id, kind, and size.

Supports the same revision forms as crate::revwalk::rev_parse::resolve_revision (for example HEAD~2, v1^{tree}, main:path, @{1}, abbreviated oids).

§Errors

Returns ResolveError::UnknownRevision when the spec cannot be resolved, ResolveError::AmbiguousShortObject when a short oid is ambiguous, and ResolveError::PathNotInTree when a rev:path path is missing.

Source

pub fn verify_object( &self, spec: &str, expected: Option<ObjectKind>, ) -> Result<ObjectId, ResolveError>

Strict single-object resolution for plumbing verify (git rev-parse --verify).

Accepts one spec that names one existing object, honoring ^{type} peels. Rejects revision ranges (A..B, A...B) and revision-set excludes (^A). Verifies the object exists in the object database (full hex ids must refer to stored objects, not merely parse).

§Errors

Returns ResolveError::RevisionRange for range or set syntax, ResolveError::UnknownRevision when the spec cannot be resolved or the object is missing, ResolveError::AmbiguousShortObject for ambiguous abbreviated ids, and ResolveError::WrongObjectKind when expected is set and the peeled kind differs.

Source

pub fn resolve_ref_name( &self, spec: &str, ) -> Result<Option<ResolvedRefName>, RevParseError>

Resolve spec to ref names when it names a ref (rev-parse --abbrev-ref / --symbolic-full-name).

Returns Ok(None) when the spec does not name a ref (for example a commit oid or HEAD^{tree}).

§Errors

When DWIM finds multiple refs and core.warnAmbiguousRefs is enabled, emits Warning::AmbiguousRefname and returns Ok(None) (matching git rev-parse stdout). Other RevParseError variants cover invalid upstream / @{-N} specs.

Source

pub fn read_object_raw_for_display(&self, oid: &ObjectId) -> Result<Object>

Read uncompressed object bytes for display, following replace refs when enabled.

§Errors

Returns Error::ObjectNotFound when the object is missing.

Source

pub fn read_object_info_for_display(&self, oid: &ObjectId) -> Result<ObjectInfo>

Object kind and size for display, following replace refs when enabled.

oid names the original object. Returns metadata for its replacement when replacement is enabled, without loading loose or whole packed blob payloads.

§Errors

Returns Error::ObjectNotFound when the object is missing.

Source

pub fn with_object_stream_for_display<R>( &self, oid: &ObjectId, f: impl FnOnce(ObjectStream<'_>) -> Result<R>, ) -> Result<Option<R>>

Stream an object’s payload for display, following replace refs when enabled.

oid names the original object and f consumes the effective object’s stream. Returns Ok(Some(result)) with the callback’s result, or Ok(None) when the object is missing (without calling f). Loose and whole packed objects are inflated as the callback reads; pack deltas are reconstructed in memory.

§Errors

Propagates backend failures and errors from f. Corrupt or truncated payloads surface as std::io::Error values when reading the stream.

Source

pub fn read_object_for_display(&self, oid: &ObjectId) -> Result<ObjectContents>

Read and parse the object named by oid for display.

§Errors

Returns Error::ObjectNotFound when the object is missing and Error::CorruptObject when parsing fails.

Source§

impl Repository

Source

pub fn thread_policy(&self) -> ThreadPolicy

Explicit parallel worker overrides for this handle (--threads / embedder policy).

Source

pub fn with_thread_policy(self, policy: ThreadPolicy) -> Self

Return a copy of this repository handle with an updated parallel thread policy.

Source

pub fn environment(&self) -> &Environment

Return the Environment used to discover or open this repository.

Source

pub fn reference_unix_time(&self) -> i64

Unix timestamp for rev-parse relative date selectors (@{yesterday}, etc.).

Source

pub fn wall_clock_epoch(&self) -> i64

Wall clock used for commit dates, rerere GC, relative dates, and similar operations on this handle.

Source

pub fn identity_now(&self) -> OffsetDateTime

Self::wall_clock_epoch in this handle’s TZ, for stamping author, committer and reflog identity lines (see resolve_identity_with).

Source

pub fn identity( &self, role: IdentRole, now: OffsetDateTime, ) -> Result<Signature>

Resolve the author or committer identity Git would record for a new commit, tag, stash, or notes commit made through this handle.

Reads the handle’s Environment (GIT_AUTHOR_* / GIT_COMMITTER_*, including the *_DATE overrides) and configuration (author.*, committer.*, user.*); see resolve_signature_with.

§Parameters
  • role: author or committer.
  • now: timestamp recorded when no date override is set; usually Self::identity_now.
§Errors

Error::Identity when no usable name, email, or date is configured, and config load failures.

§Examples
use grit_lib::config::ident_resolve::IdentRole;
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let repo = Repository::init(dir.path(), &InitOptions::default())?;
match repo.identity(IdentRole::Author, repo.identity_now()) {
    Ok(author) => assert!(!author.email.is_empty()),
    Err(grit_lib::error::Error::Identity(_)) => {} // nothing configured
    Err(other) => return Err(other),
}
Source

pub fn command_runner(&self) -> Arc<dyn CommandRunner> ⓘ

Subprocess runner used for hooks, filters, and helpers.

Source

pub fn hook_stdio(&self) -> HookStdio

Where hooks run through this handle write their output (RepositoryOptions::with_hook_stdio).

Source

pub fn change_id_generator(&self) -> Arc<dyn ChangeIdGenerator> ⓘ

Generator used for random change ids on new commits.

Source

pub fn linked_worktree_discover_options(&self) -> RepositoryOptions

RepositoryOptions for discovering a linked worktree of this repository.

Inherits config discovery (Environment, command runner, diagnostics, thread policy) from the caller handle but clears worktree-specific discovery overrides so Repository::discover resolves the linked tree’s own .git gitfile and index.

Source

pub fn diagnostics(&self) -> DiagnosticsHandle

Return the diagnostic sink installed on this repository.

Source

pub fn set_diagnostics(&mut self, sink: DiagnosticsHandle)

Replace the diagnostic sink (for embedders and the CLI).

Source

pub fn network_trace_enabled(&self) -> bool

Whether network trace events should be delivered to the diagnostic sink.

Source

pub fn set_network_trace(&mut self, enabled: bool)

Enable or disable network trace events on this handle.

Source

pub fn config(&self) -> Result<Arc<ConfigSet>>

Return the merged configuration cascade for this repository.

Loads through RepoCaches on every call so global, system, include, and local config stamps stay validated (not only .git/config mtime). Prefer Self::reload_config after in-process config writes so related caches update immediately.

§Errors

Propagates errors from reading or parsing config files.

Source

pub fn reload_config(&self) -> Result<()>

Drop the in-memory config snapshot and load a fresh cascade from disk.

Call after writing .git/config (or other cascade files) through library APIs on this repository handle so subsequent Self::config and hot-path readers observe the new data.

§Errors

Propagates errors from ConfigSet::load.

Source

pub fn common_git_dir(&self) -> &Path

Common git directory for this handle (commondir when linked).

Source

pub fn refs(&self) -> &dyn RefStore

Reference storage backend for this repository.

Source

pub fn objects(&self) -> Objects<'_>

Object read/write handle for this repository.

Source

pub fn references(&self) -> References<'_>

Reference resolve/list/update and reflog read handle.

Source

pub fn index_handle(&self) -> IndexHandle<'_>

Index load/write handle.

Source

pub fn config_handle(&self) -> ConfigHandle<'_>

Merged config read and local config write handle.

Source

pub fn rev_walk(&self) -> RevWalk<'_>

Revision parse and rev-list handle.

Source

pub fn diff(&self) -> Diff<'_>

Tree, index, and worktree diff handle.

Source

pub fn remotes(&self) -> RepositoryRemotes<'_>

Remote configuration, ls-remote, fetch, and push for this repository.

Source

pub fn worktrees(&self) -> RepositoryWorktrees<'_>

Linked worktree listing and admin for this repository.

Source

pub fn stash(&self) -> RepositoryStash<'_>

Stash stack operations for this repository.

Source

pub fn notes(&self) -> RepositoryNotes<'_>

Git notes read/write for this repository.

Source

pub fn hooks(&self) -> RepositoryHooks<'_>

Hook script discovery for this repository.

Source

pub fn fsck( &self, options: &FsckOptions, progress: &mut dyn ProgressSink, cancel: &dyn Cancel, ) -> Result<FsckReport>

Check object store connectivity, refs, and optional pack indexes.

Progress is reported through progress; the library never prints.

§Errors

Propagates object-store, ref, or index failures that abort the run. A custom primary object store is validated through the objects it lists (see crate::fsck::fsck).

Source

pub fn tree_sha256( &self, oid: ObjectId, options: &TreeSha256Options, ) -> Result<TreeSha256Report>

SHA-256 content digest of a revision’s tree (tree-sha256 spec).

§Errors

Returns crate::error::Error::TreeSha256MissingSubmodules when submodule checkouts or objects needed for hashing are absent.

Source

pub fn verify_tag( &self, oid: ObjectId, options: &TagVerifyOptions, ) -> Result<TagVerification>

Verify an annotated tag’s signature and optional tree-sha256 header.

Reads the tag object by oid (not via a ref). Signature checking and digest recomputation run on separate threads when both are needed.

§Errors

See crate::tree_sha256::verify_tag.

Source

pub fn patch_id( &self, commit: &ObjectId, mode: PatchIdMode, ) -> Result<Option<ObjectId>>

Patch-ID for a single commit (merge commits and empty diffs return None).

Text diffs use unified hunks with three context lines on each side, matching git show --format= --no-ext-diff -U3 piped to git patch-id in the selected mode. Only context inside those hunks contributes to the ID.

§Errors

Propagates object database read/parse failures.

Source

pub fn reflogs(&self) -> RepositoryReflogs<'_>

Reflog listing, deletion, and expiry for this repository.

Source

pub fn bundles(&self) -> RepositoryBundles<'_>

Bundle create, verify, list-heads, and unbundle for this repository.

Source

pub fn repack(&self, opts: &RepackOptions) -> Result<RepackReport>

Repack reachable objects into a single pack and prune redundant storage.

§Errors

Propagates pack, prune, or unsupported-backend failures from crate::maintenance::repack.

Source

pub fn with_ref_store(self, store: Arc<dyn RefStore>) -> Self

Replace the ref store (embedders injecting crate::refs::store::MemoryRefStore).

Source

pub fn resolve_worktree_pathspec( &self, pathspec: &str, prefix: Option<&str>, ) -> Result<String, PathspecResolveError>

Resolve one argv pathspec against this repository’s work tree.

prefix is the work-tree-relative directory the pathspec was typed in (None at the root). Magic pathspecs pass through; plain paths are joined with prefix, normalized, and NFC-normalized when core.precomposeunicode is on and the filesystem aliases NFD/NFC spellings. That decision is computed once per handle, so resolving many pathspecs costs no config reload or filesystem probe per path.

§Errors

crate::pathspec::PathspecResolveError::NeedsWorkTree for a bare repository, and crate::pathspec::PathspecResolveError::OutsideRepository when pathspec resolves outside the work tree.

Source

pub fn paths_match_pathspecs( &self, path: &str, specs: &[String], ) -> Result<bool>

Whether path is selected by the resolved pathspec list specs.

Shorthand for Self::pathspec_matcher followed by crate::pathspec::PathspecMatcher::matches; build the matcher once instead when filtering many paths with specs that may carry :(attr:...) magic.

§Errors

Same as Self::pathspec_matcher.

Source

pub fn pathspec_matcher<'s>( &self, specs: &'s [String], ) -> Result<PathspecMatcher<'s>>

Prepare specs (resolved pathspecs) for matching many paths in this repository.

The matcher applies Git’s list semantics and every pathspec magic word, including :(attr:...), which is evaluated against this repository’s attributes: the work-tree stack (global file, root and nested .gitattributes, info/attributes), or info/attributes and the global file for a bare repository. Attributes are read only when a spec carries attr magic, once per matcher, from the per-handle cache; [attr] macros are expanded and core.ignorecase makes attribute patterns case-insensitive. Paths and specs follow core.precomposeunicode.

§Errors

Only when a spec carries attr magic: Error::InvalidAttrPathspec for a malformed or repeated attr: clause, or the error from loading config or the attribute files (for example an unreadable core.attributesFile setting or a poisoned cache lock).

Source

pub fn pathspec_cwd_prefix(&self) -> Option<&str>

Repository-relative prefix of the process cwd for argv pathspecs (no trailing slash).

Matches Git GIT_PREFIX / pathdiff semantics used by git log --, git rev-list --, and git blame from a subdirectory.

Source

pub fn pathspec_argv_prefix<'a>(&'a self, pathspec: &str) -> Option<&'a str>

Cwd prefix for one argv pathspec (None for :(top) / :/, which stay repo-root-relative).

Source

pub fn resolve_rev_walk_pathspecs( &self, paths: &[String], ) -> Result<Vec<String>>

Resolve argv path operands for revision walks (log, revs, rev-list, …).

Literal segments are interpreted relative to the process cwd under the work tree, like git diff -- and Git pathspec cwd rules. Exclude-only lists gain Git’s implicit cwd positive prefix when appropriate.

§Errors

Returns Error::PathError when a pathspec resolves outside the work tree.

Source

pub fn git_dir(&self) -> &Path

Absolute path to the git directory (.git/ or bare repository root).

Source

pub fn work_tree(&self) -> Option<&Path>

Absolute work tree path for non-bare repositories.

Source

pub fn odb(&self) -> &Odb

Object database for this repository.

Source

pub fn prefetch_promised(&self, oids: &[ObjectId]) -> Result<()>

Fetch missing promisor objects in one batch before checkout or other bulk reads.

§Errors

Returns crate::error::Error::Message when no fetcher is installed, or transport failures.

Source

pub fn discovery_info(&self) -> DiscoveryInfo

Discovery provenance for safe-directory and setup tracing.

Source

pub fn init(path: &Path, options: &InitOptions) -> Result<Self>

Initialise a repository at path and return an open handle.

§Errors

Propagates filesystem and layout errors from the underlying init helpers.

Source

pub fn init_with_outcome( path: &Path, options: &InitOptions, ) -> Result<(Self, InitOutcome)>

Like Self::init, but also reports whether the repository was reinitialized and the effective initial branch name.

§Errors

Propagates filesystem and layout errors from the underlying init helpers.

Source

pub fn open(path: &Path, options: &RepositoryOptions) -> Result<Self>

Open or resolve a repository at path using options.

When RepositoryOptions::open_for_serving is set, path is resolved like smart-HTTP serving (work tree, bare root, or path.git). Otherwise path is the git directory and RepositoryOptions::work_tree selects the work tree.

§Errors

Returns Error::NotARepository when the layout is invalid.

Source

pub fn discover( start: Option<&Path>, options: &RepositoryOptions, ) -> Result<Self>

Discover a repository starting from start (defaults to Environment::cwd when None).

Source

pub fn write_largest_pack_bitmap( &self, options: &PackBitmapWriteOptions, now: SystemTime, ) -> Result<PathBuf, PackBitmapWriteError>

Write a .bitmap sidecar for the largest pack in the primary object store.

§Errors

Returns crate::pack_bitmap::PackBitmapWriteError when no pack index exists or the pack is not closed under reachability from repository refs.

Source

pub fn is_bare(&self) -> bool

Whether this is a bare repository (no working tree).

Source§

impl Repository

Source

pub fn enforce_safe_directory(&self) -> Result<()>

Enforce safe.directory ownership checks, matching upstream behavior.

When GIT_TEST_ASSUME_DIFFERENT_OWNER=1, ownership is considered unsafe unless a matching safe.directory value is configured in system/global/ command scopes (repository-local config is ignored).

Source

pub fn verify_safe_for_clone_source(&self) -> Result<()>

Verify the repository is safe to use as a git clone source (local clone).

When GIT_TEST_ASSUME_DIFFERENT_OWNER is set, applies the same safe.directory rules as discovery. Otherwise checks filesystem ownership of the git directory only (matching Git’s die_upon_dubious_ownership for clone).

Source§

impl Repository

Source

pub fn head_commit(&self) -> Result<ObjectId>

The commit HEAD points at, whether through a branch or detached.

HEAD is read with resolve_head_for_repository, so injected ref stores are honoured. Use that function instead when the caller also needs the branch name or must treat an unborn branch as a normal state.

§Errors
  • Error::UnbornHead when HEAD names a branch with no commits yet.
  • Error::InvalidHead when HEAD is missing or names something that is not a ref.
  • Ref store read failures while resolving HEAD.

Trait Implementations§

Source§

impl Debug for Repository

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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