Skip to main content

RepositoryOptions

Struct RepositoryOptions 

Source
#[non_exhaustive]
pub struct RepositoryOptions {
Show 17 fields pub environment: Environment, pub command_runner: Arc<dyn CommandRunner>, pub change_id_generator: Arc<dyn ChangeIdGenerator>, pub diagnostics: Arc<dyn DiagnosticSink + Send + Sync>, pub network_trace: bool, pub reference_unix_time: Option<i64>, pub thread_policy: ThreadPolicy, pub work_tree: Option<PathBuf>, pub object_store: Option<Arc<dyn WritableObjectStore>>, pub odb_builder: Option<OdbBuilder>, pub ref_store: Option<Arc<dyn RefStore>>, pub initial_branch: Option<String>, pub validate_repository_format: bool, pub open_for_serving: bool, pub promisor_fetcher: Option<Arc<dyn PromisorFetcher>>, pub hook_stdio: HookStdio, pub reftable_write: ReftableWriteOptions, /* private fields */
}
Expand description

Options passed to crate::repo::Repository::open, crate::repo::Repository::discover, and related entry points.

§Opening a normal repository

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::repo::{InitOptions, Repository};

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

§Discovering from a working directory

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::repo::{InitOptions, Repository};

let dir = tempfile::tempdir()?;
Repository::init(dir.path(), &InitOptions::default())?;
let repo = Repository::discover(Some(dir.path()), &RepositoryOptions::empty())?;
assert!(repo.work_tree().is_some());

§Bare repository

Open the bare git directory; leave Self::work_tree unset.

§Linked worktree

Open the worktree’s admin directory (under worktrees/) and set Self::work_tree to the linked checkout path, or call Repository::discover from the linked checkout with environment overrides cleared (no GIT_DIR / GIT_WORK_TREE).

§Injected ref store and custom object store

With both stores injected the git directory may be missing: nothing is read from its layout, though config and the index are still looked up there.

use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::store::MemoryStore;
use grit_lib::objects::{HashAlgo, ObjectKind};
use grit_lib::refs::store::MemoryRefStore;
use grit_lib::repo::Repository;

let dir = tempfile::tempdir()?;
let git_dir = dir.path().join("in-memory.git");
let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
let repo = Repository::open(
    &git_dir,
    &RepositoryOptions::empty()
        .with_object_store(store.clone())
        .with_ref_store(Arc::new(MemoryRefStore::new()))
        .with_initial_branch("main"),
)?;
let oid = repo.odb().write(ObjectKind::Blob, b"hello")?;
assert!(grit_lib::objects::odb::store::ObjectStore::contains(store.as_ref(), &oid)?);
assert!(!git_dir.exists());

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§environment: Environment

Discovery and configuration environment.

§command_runner: Arc<dyn CommandRunner>

Subprocess runner for hooks, filters, and helpers.

§change_id_generator: Arc<dyn ChangeIdGenerator>

Random bytes for new change ids (grit.changeIds).

§diagnostics: Arc<dyn DiagnosticSink + Send + Sync>

Where non-fatal warnings and trace events are delivered.

§network_trace: bool

When true, network operations may emit crate::diagnostics::Trace::Network events.

§reference_unix_time: Option<i64>

Wall-clock reference for rev-parse date selectors; embedders set explicitly.

§thread_policy: ThreadPolicy

Parallel worker overrides (--threads in the CLI).

§work_tree: Option<PathBuf>

Work tree path for crate::repo::Repository::open (non-bare repos).

§object_store: Option<Arc<dyn WritableObjectStore>>

Primary object store to use instead of the files layout under objects/ (see Self::with_object_store).

§odb_builder: Option<OdbBuilder>

Read layers, attached commit-graph and alternates policy (see crate::odb::OdbBuilder).

§ref_store: Option<Arc<dyn RefStore>>

Ref backend to use instead of opening one from the git directory.

§initial_branch: Option<String>

When the ref store has no HEAD after open, seed an unborn branch at refs/heads/<name>.

§validate_repository_format: bool

When false, skip crate::repo::validate_repo_format during open.

§open_for_serving: bool

When true, crate::repo::Repository::open resolves path like wire-protocol serving.

§promisor_fetcher: Option<Arc<dyn PromisorFetcher>>

Optional on-demand fetcher for partial-clone promisor objects.

§hook_stdio: HookStdio

Where hook subprocesses write their output (captured by default).

§reftable_write: ReftableWriteOptions

Overrides for reftable stack writes on repositories opened with these options.

Implementations§

Source§

impl RepositoryOptions

Source

pub fn empty() -> RepositoryOptions

Options with Environment::empty: no home directory, no global config and, on Windows, no system config.

Operations then ignore settings such as core.autocrlf, user.name, safe.directory and core.excludesFile from the user’s system and global config, so results can differ from git on the same repository. Meant for tests and repositories the caller created; use Self::from_process for a user’s repositories.

Source

pub fn from_process() -> RepositoryOptions

Options with Environment::capture_process: the embedder equivalent of running git or grit in this process.

System and global config apply (core.autocrlf, identity, safe.directory, core.excludesFile, credential helpers), found through HOME, GIT_CONFIG_* and, on Windows, ProgramFiles. Call it at the program boundary, not from library code.

Source

pub fn with_environment(environment: Environment) -> RepositoryOptions

Options around an explicit Environment snapshot.

This is an associated constructor, not a builder method: write RepositoryOptions::with_environment(env).with_command_runner(runner).

Source

pub fn with_command_runner( self, runner: Arc<dyn CommandRunner>, ) -> RepositoryOptions

Override the injectable subprocess runner used for hooks and filters.

Source

pub fn with_change_id_generator( self, generator: Arc<dyn ChangeIdGenerator>, ) -> RepositoryOptions

Override the generator used for random change ids on new commits.

Source

pub fn with_work_tree(self, work_tree: impl Into<PathBuf>) -> RepositoryOptions

Attach an explicit work tree for crate::repo::Repository::open.

Source

pub fn with_object_store( self, store: Arc<dyn WritableObjectStore>, ) -> RepositoryOptions

Use store as the repository’s primary object store instead of the files layout under objects/.

Writes and primary reads go through this backend, including commits, staging ([crate::porcelain::add::stage]), merges, stash, notes, and bundle creation. Maintenance::fsck validates the objects this store lists. Received packs are written into it object by object: ingest_received_pack and Bundle::unbundle resolve every delta and call WritableObjectStore::write instead of installing a pack under objects/pack/. Fetch, push, pull, bundles and clone_into read and write objects through it.

Repository::open still resolves the objects/ directory (honoring GIT_OBJECT_DIRECTORY), but never reads or writes objects there, and the directory need not exist. Alternates are off unless OdbBuilder::alternates turns them on. Partial clone filters and filesystem maintenance (crate::odb::Odb::write_commit_graph, repack, multi-pack-index) refuse with RepositoryError::UnsupportedObjectStore. Garbage collection and pruning (crate::odb::Odb::gc, [crate::maintenance::gc], [crate::maintenance::prune_loose_objects]) work when the store can delete objects (WritableObjectStore::as_prunable) and refuse with FilesOnlyOperation::Prune otherwise.

The store’s ObjectStore::hash_algo must match the repository’s object format, or Repository::open fails with RepositoryError::ObjectFormatMismatch.

§Without a git directory

A bare repository opened with this store, a Self::with_ref_store backend and its config in the Environment (through Environment::push_config_override, with Environment::git_config_nosystem set to keep /etc/gitconfig out) needs nothing on disk. The git directory may be a path that does not exist, and grit-lib does not create it. <git_dir>/config is still read when it exists.

AreaWithout a git directory
Objects, trees and commits (Repository::objects)Work through the store.
Refs, reflogs, HEAD and ref transactions (Repository::references)Work through the ref store.
Config (Repository::config)Comes from the Environment.
Rev-parse, revwalk and logWork.
Tree diff, write_merge_tree and blame at a commitWork.
Notes, and bundles written to any std::io::Write (RepositoryBundles::write_to)Work.
History edits (History::reword, History::apply)Work.
Fetch from a path or URLWorks. The pack is spooled in the system temp directory and removed after ingest, and FETCH_HEAD is not written.
HooksA missing hooks directory means no hooks.
The index, staging and worktree commitsOut of scope: the index, COMMIT_EDITMSG and merge, revert and rebase state live in the git directory, which staging creates.
Work-tree operations (checkout, switch, status, reset, stash)Out of scope: they need a work tree and an index.
Linked worktreesOut of scope: their admin directories live under worktrees/.
rerere and sparse-checkoutOut of scope: their state is kept in files in the git directory.
Hooks that expect GIT_DIR on diskOut of scope: objects and refs held by the stores are invisible to other programs, such as the system git.
gc and pruneWork when the store can delete objects (WritableObjectStore::as_prunable), as described above.
Repack, commit-graph and multi-pack-index filesRefused with RepositoryError::UnsupportedObjectStore.
§Examples
use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::odb::store::{MemoryStore, ObjectStore};
use grit_lib::objects::{HashAlgo, ObjectKind};
use grit_lib::repo::{InitOptions, Repository};

let dir = tempfile::tempdir()?;
Repository::init(dir.path(), &InitOptions::default())?;
let store = Arc::new(MemoryStore::new(HashAlgo::Sha1));
let repo = Repository::open(
    &dir.path().join(".git"),
    &RepositoryOptions::empty()
        .with_object_store(store.clone())
        .with_work_tree(dir.path()),
)?;
let oid = repo.odb().write(ObjectKind::Blob, b"hello")?;
assert!(store.contains(&oid)?);

A bare repository with no git directory, its config held in the Environment:

use std::sync::Arc;

use grit_lib::config::environment::{ConfigOverride, Environment, RepositoryOptions};
use grit_lib::objects::odb::store::MemoryStore;
use grit_lib::objects::HashAlgo;
use grit_lib::refs::store::MemoryRefStore;
use grit_lib::repo::Repository;

let mut env = Environment::empty();
env.git_config_nosystem = Some("1".to_owned());
env.push_config_override(&ConfigOverride::new("user.name", Some("Ada".to_owned()))?);
let dir = tempfile::tempdir()?;
let git_dir = dir.path().join("never-created.git");
let repo = Repository::open(
    &git_dir,
    &RepositoryOptions::with_environment(env)
        .with_object_store(Arc::new(MemoryStore::new(HashAlgo::Sha1)))
        .with_ref_store(Arc::new(MemoryRefStore::new()))
        .with_initial_branch("main"),
)?;
assert!(repo.is_bare());
assert_eq!(repo.config().snapshot()?.get("user.name")?.as_deref(), Some("Ada"));
assert!(!git_dir.exists());
Source

pub fn with_odb_builder(self, builder: OdbBuilder) -> RepositoryOptions

Layer read-only stores, a commit-graph, or an alternates override over the primary object store (see crate::odb::OdbBuilder).

Source

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

Use store as the ref backend instead of opening one from the git directory.

Source

pub fn with_initial_branch(self, branch: impl Into<String>) -> RepositoryOptions

Seed HEAD at refs/heads/<branch> when the ref store has no HEAD after open.

Source

pub fn without_format_validation(self) -> RepositoryOptions

Skip repository format validation when opening (discovery follow-up paths).

Source

pub fn for_serving(self) -> RepositoryOptions

Resolve path for smart-HTTP / upload-pack serving instead of a bare git directory.

Source

pub fn with_diagnostics( self, diagnostics: Arc<dyn DiagnosticSink + Send + Sync>, ) -> RepositoryOptions

Override the diagnostic sink for warnings and trace events.

Source

pub fn with_reftable_write( self, reftable_write: ReftableWriteOptions, ) -> RepositoryOptions

Override reftable write behavior (for example disable auto-compaction in tests).

Source

pub fn reftable_write(&self) -> ReftableWriteOptions

Reftable write overrides installed on these options.

Source

pub fn with_ownership_check( self, check: Arc<dyn OwnershipCheck>, ) -> RepositoryOptions

Replace the ownership check used during discovery and clone safety checks.

The default crate::ownership_check::SystemOwnershipCheck compares the effective Unix uid against repository paths. Custom implementations can treat repositories as always foreign so safe.directory always applies (sandboxes and tests).

Source

pub fn ownership_check(&self) -> Arc<dyn OwnershipCheck> ⓘ

Ownership check installed on these options.

Source

pub fn uses_default_ownership_check(&self) -> bool

Whether these options still use the shared default SystemOwnershipCheck.

Source

pub fn with_hook_stdio(self, hook_stdio: HookStdio) -> RepositoryOptions

Choose whether hooks run by repositories opened with these options have their output captured (HookStdio::Capture, the default) or write straight to this process’s stderr.

Source

pub fn with_network_trace(self, network_trace: bool) -> RepositoryOptions

Enable or disable network trace events.

Source

pub fn with_promisor_fetcher( self, fetcher: Option<Arc<dyn PromisorFetcher>>, ) -> RepositoryOptions

Install a promisor on-demand object fetcher for repositories opened with these options.

Trait Implementations§

Source§

impl Clone for RepositoryOptions

Source§

fn clone(&self) -> RepositoryOptions

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 Debug for RepositoryOptions

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for RepositoryOptions

Source§

fn default() -> RepositoryOptions

Returns the “default value” for a type. 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> 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.