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:
Self::reload_configafter writing config throughcrate::config::ConfigHandleor other in-process library APIs on this handle.- Hook and filter subprocesses may rewrite config;
crate::hooks::run_hook_optsreloads the snapshot after hooks finish when aRepositoryis provided. - External edits (another process, or the system
gitbinary) are picked up on the nextSelf::configcall, which revalidates file stamps once per call—not on every internal read. - Open a new
Repositoryto observe ref or config changes made elsewhere without callingSelf::reload_config(for example arefs/replace/*ref created by systemgit).
§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
impl Repository
Sourcepub fn ignore_check(
&self,
paths: &[String],
index: &Index,
) -> Result<Vec<IgnoreCheck>>
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 bynormalize_repo_relative).index- current index; tracked paths are treated as not ignored.
§Errors
Returns Error::Io when loading exclude files fails.
Source§impl Repository
impl Repository
Sourcepub fn write_commit_graph(
&self,
opts: &CommitGraphOptions,
) -> Result<CommitGraphWriteReport>
pub fn write_commit_graph( &self, opts: &CommitGraphOptions, ) -> Result<CommitGraphWriteReport>
Sourcepub fn write_midx(&self, opts: &MidxOptions) -> Result<MidxWriteReport>
pub fn write_midx(&self, opts: &MidxOptions) -> Result<MidxWriteReport>
Source§impl Repository
impl Repository
Sourcepub fn revision_label(&self, spec: &str) -> Result<Option<RevisionLabel>>
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.
Sourcepub fn resolve(&self, spec: &str) -> Result<ResolvedObject, ResolveError>
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.
Sourcepub fn verify_object(
&self,
spec: &str,
expected: Option<ObjectKind>,
) -> Result<ObjectId, ResolveError>
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.
Sourcepub fn resolve_ref_name(
&self,
spec: &str,
) -> Result<Option<ResolvedRefName>, RevParseError>
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.
Sourcepub fn read_object_raw_for_display(&self, oid: &ObjectId) -> Result<Object>
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.
Sourcepub fn read_object_info_for_display(&self, oid: &ObjectId) -> Result<ObjectInfo>
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.
Sourcepub fn with_object_stream_for_display<R>(
&self,
oid: &ObjectId,
f: impl FnOnce(ObjectStream<'_>) -> Result<R>,
) -> Result<Option<R>>
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.
Sourcepub fn read_object_for_display(&self, oid: &ObjectId) -> Result<ObjectContents>
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
impl Repository
Sourcepub fn thread_policy(&self) -> ThreadPolicy
pub fn thread_policy(&self) -> ThreadPolicy
Explicit parallel worker overrides for this handle (--threads / embedder policy).
Sourcepub fn with_thread_policy(self, policy: ThreadPolicy) -> Self
pub fn with_thread_policy(self, policy: ThreadPolicy) -> Self
Return a copy of this repository handle with an updated parallel thread policy.
Sourcepub fn environment(&self) -> &Environment
pub fn environment(&self) -> &Environment
Return the Environment used to discover or open this repository.
Sourcepub fn reference_unix_time(&self) -> i64
pub fn reference_unix_time(&self) -> i64
Unix timestamp for rev-parse relative date selectors (@{yesterday}, etc.).
Sourcepub fn wall_clock_epoch(&self) -> i64
pub fn wall_clock_epoch(&self) -> i64
Wall clock used for commit dates, rerere GC, relative dates, and similar operations on this handle.
Sourcepub fn identity_now(&self) -> OffsetDateTime
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).
Sourcepub fn identity(
&self,
role: IdentRole,
now: OffsetDateTime,
) -> Result<Signature>
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; usuallySelf::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),
}Sourcepub fn command_runner(&self) -> Arc<dyn CommandRunner> ⓘ
pub fn command_runner(&self) -> Arc<dyn CommandRunner> ⓘ
Subprocess runner used for hooks, filters, and helpers.
Sourcepub fn hook_stdio(&self) -> HookStdio
pub fn hook_stdio(&self) -> HookStdio
Where hooks run through this handle write their output
(RepositoryOptions::with_hook_stdio).
Sourcepub fn change_id_generator(&self) -> Arc<dyn ChangeIdGenerator> ⓘ
pub fn change_id_generator(&self) -> Arc<dyn ChangeIdGenerator> ⓘ
Generator used for random change ids on new commits.
Sourcepub fn linked_worktree_discover_options(&self) -> RepositoryOptions
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.
Sourcepub fn diagnostics(&self) -> DiagnosticsHandle
pub fn diagnostics(&self) -> DiagnosticsHandle
Return the diagnostic sink installed on this repository.
Sourcepub fn set_diagnostics(&mut self, sink: DiagnosticsHandle)
pub fn set_diagnostics(&mut self, sink: DiagnosticsHandle)
Replace the diagnostic sink (for embedders and the CLI).
Sourcepub fn network_trace_enabled(&self) -> bool
pub fn network_trace_enabled(&self) -> bool
Whether network trace events should be delivered to the diagnostic sink.
Sourcepub fn set_network_trace(&mut self, enabled: bool)
pub fn set_network_trace(&mut self, enabled: bool)
Enable or disable network trace events on this handle.
Sourcepub fn config(&self) -> Result<Arc<ConfigSet>>
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.
Sourcepub fn reload_config(&self) -> Result<()>
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.
Sourcepub fn common_git_dir(&self) -> &Path
pub fn common_git_dir(&self) -> &Path
Common git directory for this handle (commondir when linked).
Sourcepub fn references(&self) -> References<'_>
pub fn references(&self) -> References<'_>
Reference resolve/list/update and reflog read handle.
Sourcepub fn index_handle(&self) -> IndexHandle<'_>
pub fn index_handle(&self) -> IndexHandle<'_>
Index load/write handle.
Sourcepub fn config_handle(&self) -> ConfigHandle<'_>
pub fn config_handle(&self) -> ConfigHandle<'_>
Merged config read and local config write handle.
Sourcepub fn remotes(&self) -> RepositoryRemotes<'_>
pub fn remotes(&self) -> RepositoryRemotes<'_>
Remote configuration, ls-remote, fetch, and push for this repository.
Sourcepub fn worktrees(&self) -> RepositoryWorktrees<'_>
pub fn worktrees(&self) -> RepositoryWorktrees<'_>
Linked worktree listing and admin for this repository.
Sourcepub fn stash(&self) -> RepositoryStash<'_>
pub fn stash(&self) -> RepositoryStash<'_>
Stash stack operations for this repository.
Sourcepub fn notes(&self) -> RepositoryNotes<'_>
pub fn notes(&self) -> RepositoryNotes<'_>
Git notes read/write for this repository.
Sourcepub fn hooks(&self) -> RepositoryHooks<'_>
pub fn hooks(&self) -> RepositoryHooks<'_>
Hook script discovery for this repository.
Sourcepub fn fsck(
&self,
options: &FsckOptions,
progress: &mut dyn ProgressSink,
cancel: &dyn Cancel,
) -> Result<FsckReport>
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).
Sourcepub fn tree_sha256(
&self,
oid: ObjectId,
options: &TreeSha256Options,
) -> Result<TreeSha256Report>
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.
Sourcepub fn verify_tag(
&self,
oid: ObjectId,
options: &TagVerifyOptions,
) -> Result<TagVerification>
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
Sourcepub fn patch_id(
&self,
commit: &ObjectId,
mode: PatchIdMode,
) -> Result<Option<ObjectId>>
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.
Sourcepub fn reflogs(&self) -> RepositoryReflogs<'_>
pub fn reflogs(&self) -> RepositoryReflogs<'_>
Reflog listing, deletion, and expiry for this repository.
Sourcepub fn bundles(&self) -> RepositoryBundles<'_>
pub fn bundles(&self) -> RepositoryBundles<'_>
Bundle create, verify, list-heads, and unbundle for this repository.
Sourcepub fn repack(&self, opts: &RepackOptions) -> Result<RepackReport>
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.
Sourcepub fn with_ref_store(self, store: Arc<dyn RefStore>) -> Self
pub fn with_ref_store(self, store: Arc<dyn RefStore>) -> Self
Replace the ref store (embedders injecting crate::refs::store::MemoryRefStore).
Sourcepub fn resolve_worktree_pathspec(
&self,
pathspec: &str,
prefix: Option<&str>,
) -> Result<String, PathspecResolveError>
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.
Sourcepub fn paths_match_pathspecs(
&self,
path: &str,
specs: &[String],
) -> Result<bool>
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.
Sourcepub fn pathspec_matcher<'s>(
&self,
specs: &'s [String],
) -> Result<PathspecMatcher<'s>>
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).
Sourcepub fn pathspec_cwd_prefix(&self) -> Option<&str>
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.
Sourcepub fn pathspec_argv_prefix<'a>(&'a self, pathspec: &str) -> Option<&'a str>
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).
Sourcepub fn resolve_rev_walk_pathspecs(
&self,
paths: &[String],
) -> Result<Vec<String>>
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.
Sourcepub fn git_dir(&self) -> &Path
pub fn git_dir(&self) -> &Path
Absolute path to the git directory (.git/ or bare repository root).
Sourcepub fn prefetch_promised(&self, oids: &[ObjectId]) -> Result<()>
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.
Sourcepub fn discovery_info(&self) -> DiscoveryInfo
pub fn discovery_info(&self) -> DiscoveryInfo
Discovery provenance for safe-directory and setup tracing.
Sourcepub fn init(path: &Path, options: &InitOptions) -> Result<Self>
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.
Sourcepub fn init_with_outcome(
path: &Path,
options: &InitOptions,
) -> Result<(Self, InitOutcome)>
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.
Sourcepub fn open(path: &Path, options: &RepositoryOptions) -> Result<Self>
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.
Sourcepub fn discover(
start: Option<&Path>,
options: &RepositoryOptions,
) -> Result<Self>
pub fn discover( start: Option<&Path>, options: &RepositoryOptions, ) -> Result<Self>
Discover a repository starting from start (defaults to Environment::cwd when None).
Sourcepub fn write_largest_pack_bitmap(
&self,
options: &PackBitmapWriteOptions,
now: SystemTime,
) -> Result<PathBuf, PackBitmapWriteError>
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§impl Repository
impl Repository
Sourcepub fn enforce_safe_directory(&self) -> Result<()>
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).
Sourcepub fn verify_safe_for_clone_source(&self) -> Result<()>
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
impl Repository
Sourcepub fn head_commit(&self) -> Result<ObjectId>
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::UnbornHeadwhenHEADnames a branch with no commits yet.Error::InvalidHeadwhenHEADis missing or names something that is not a ref.- Ref store read failures while resolving
HEAD.