# Repository

> Open and discover Git repositories with an explicit Environment, read git-dir vs work tree, load config, and handle grit_lib::Error.

A [`Repository`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) is the main handle for grit-lib. Use [`Repository::git_dir`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html), [`Repository::work_tree`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html), and [`Repository::odb`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) for paths and the object store; discovery provenance is available through [`DiscoveryInfo`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.DiscoveryInfo.html) via [`Repository::discovery_info`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html). The [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) used to open the handle is returned by [`Repository::environment`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html).

## Environment

[`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) holds discovery and config variables (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_CEILING_DIRECTORIES`, `GIT_CONFIG_*`, home paths, `cwd`, and related fields) without reading the process environment inside the library. Construct one with `Environment::capture_process()` (an explicit snapshot of the calling process, which is what the `grit` CLI uses), `Environment::from_vars()` (parse an iterator of `(key, value)` pairs plus an explicit working directory) or `Environment::empty()` (no variables: no home directory, so no global config, and no Git for Windows system config). See [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html).

To point at a specific repository or override config for one operation (what `grit -C`, `--git-dir`, `--work-tree` and `-c` do), use `Environment::with_git_dir` and `Environment::with_work_tree` (relative paths resolve against the environment's `cwd`), and parse `key=value` into a [`ConfigOverride`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.ConfigOverride.html) for `Environment::push_config_override`. Overrides are stored in `GIT_CONFIG_PARAMETERS` form, so they load with command-line scope and reach hooks through `Environment::subprocess_environment`.

The `grit` CLI builds an environment from the process in `grit-cli` and passes it into discovery. A tool that works on a user's repositories should do the same so system and global config (`core.autocrlf`, identity, `safe.directory`, `core.excludesFile`, credential helpers) apply as they do for `git`: open with [`RepositoryOptions::from_process`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.from_process), or snapshot the variables you care about once and pass them through [`RepositoryOptions::with_environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_environment), then call [`Repository::discover`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) or [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html). [`RepositoryOptions::empty`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.empty) is for hermetic use such as tests.

Create new repositories with [`Repository::init`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) and [`InitOptions`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.InitOptions.html); the call returns `(Repository, InitOutcome)` so callers can read what was written on disk (for example the initial branch name). Pass [`RepositoryOptions`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) through [`InitOptions::with_repository_options`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.InitOptions.html#method.with_repository_options) and the returned handle keeps them, as if opened with them: the environment (which also resolves `init.defaultBranch`), command runner, diagnostics and injected stores. The default [`InitOptions`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.InitOptions.html) leaves the handle hermetic, like [`RepositoryOptions::empty`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.empty). Custom object and ref backends use [`RepositoryOptions::with_object_store`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_object_store) (read layers through [`RepositoryOptions::with_odb_builder`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_odb_builder)) and [`RepositoryOptions::with_ref_store`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_ref_store), with [`Repository::init`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.init) (which then creates no `objects/` or `refs/` for them; see [Object stores](https://grit-scm.com/docs/library/repository/object-stores.md/index.md#creating-a-repository-on-your-stores)), [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) or [`Repository::discover`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html).

[`ConfigSet::load`](https://docs.rs/grit-lib/latest/grit_lib/config/struct.ConfigSet.html) takes `&Environment` as its first argument and always parses the cascade from disk (no process-global cache). Repository-scoped memoization lives on each open handle: [`Repository::config`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) returns a [`Config`](https://docs.rs/grit-lib/latest/grit_lib/config/struct.Config.html) handle backed by [`RepoCaches`](https://docs.rs/grit-lib/latest/grit_lib/repo/caches/struct.RepoCaches.html) (config cascade, gitattributes stacks, filter-process drivers, precompose flags, and related state). Call [`Config::snapshot`](https://docs.rs/grit-lib/latest/grit_lib/config/struct.Config.html#method.snapshot) when you need an `Arc<ConfigSet>`.

## Command runner

Hooks, clean/smudge filters, credential helpers, signing, SSH transport, and similar features spawn subprocesses through a [`CommandRunner`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/trait.CommandRunner.html) stored on the repository (via [`RepositoryOptions::command_runner`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html)). The default is [`SystemCommandRunner`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/struct.SystemCommandRunner.html), which is the only non-test code path that calls `std::process::Command`. Tests and embedders can install [`RecordingRunner`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/struct.RecordingRunner.html) or a custom runner to assert argv, environment, and stdin without executing real programs. Hook failures surface as [`HookError`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/hooks/enum.HookError.html); shell filter subprocess failures use [`FilterError`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.FilterError.html). When a `filter.<driver>.required` filter fails, staging, status and checkout return [`WorktreeError::Filter`](https://docs.rs/grit-lib/latest/grit_lib/worktree/enum.WorktreeError.html#variant.Filter) and never fall back to unfiltered content. A filter that cannot be started at all is `FilterError::ExternalFilterSpawnFailed`, which carries the program and the OS error. An optional filter that fails leaves the content unfiltered, as Git does.

## Discover vs open

Call [`Repository::discover`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) when you have a working directory and want Git-style upward search. Call [`Repository::open`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) when you already know the git directory; set [`RepositoryOptions::work_tree`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) for non-bare layouts, [`RepositoryOptions::for_serving`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) for smart-HTTP paths, and [`RepositoryOptions::without_format_validation`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) when discovery must open before format checks.

After a handle is open, [`Repository::discovery_info`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) returns [`DiscoveryInfo`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.DiscoveryInfo.html) (whether discovery started from an explicit git directory, the discovery root, and related metadata). [`RepositoryLocation`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.RepositoryLocation.html) is the path-oriented view of the same layout (`From<&Repository>`); use it when you already have a handle and need git-dir vs work-tree paths without opening again.

Ownership during discovery goes through [`RepositoryOptions::ownership_check`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.ownership_check) ([`OwnershipCheck`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/trait.OwnershipCheck.html)). The default [`SystemOwnershipCheck`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/struct.SystemOwnershipCheck.html) matches Git: owned repositories open immediately; foreign-owned paths require `safe.directory`. Embedders and tests install a custom check with [`RepositoryOptions::with_ownership_check`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_ownership_check) (for example one that sets [`always_apply_safe_directory`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/trait.OwnershipCheck.html#method.always_apply_safe_directory) instead of reading `GIT_TEST_ASSUME_DIFFERENT_OWNER`).

Bare repositories return `None` from `Repository::work_tree`. When a handle has a work tree, [`Repository::is_bare`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.is_bare) is `false`, even if `core.bare` is `true` (for example a linked checkout of a bare repository, or opening the bare git directory with an explicit `GIT_WORK_TREE` / [`RepositoryOptions::work_tree`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html)). Linked worktrees and gitfile indirection are handled during discovery so `Repository::git_dir` always points at the directory that contains `objects/`.

Both paths are canonical (symlinks resolved). On Windows they use the plain `C:\...` or `\\server\share\...` spelling, so you can compare them with your own paths, use `starts_with` and show them to users. The `\\?\` form that `std::fs::canonicalize` returns is kept only for a path that cannot be written any other way, such as one longer than `MAX_PATH`. If your path may be relative or go through a symlink, pass both sides through [`path_for_disk_compare`](https://docs.rs/grit-lib/latest/grit_lib/config/git_path/fn.path_for_disk_compare.html) before comparing.

## Config

`Repository::config` returns a lazily loaded snapshot of the merged cascade (system / global / local / worktree / environment overrides). Prefer it on hot paths instead of calling `ConfigSet::load` repeatedly. Keys use Git’s dotted names (`user.name`, `core.bare`, …).

## Typed handles

Core engine areas use thin handles on `Repository` (no duplicated logic):

| Method | Handle | Role |
| --- | --- | --- |
| [`objects`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) | [`Objects`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.Objects.html) | read/write/contains for the ODB |
| [`references`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) | [`References`](https://docs.rs/grit-lib/latest/grit_lib/refs/struct.References.html) | resolve, list, update refs; read reflog |
| [`reflogs`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) | [`RepositoryReflogs`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryReflogs.html) | list reflog refs, show/delete/expire entries |
| [`index`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) | [`IndexFile`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexFile.html) | load/write the index |
| [`config`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.config) | [`Config`](https://docs.rs/grit-lib/latest/grit_lib/config/struct.Config.html) | merged get; local set + reload |
| [`revwalk`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) | [`RevWalk`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html) | rev-parse specs; rev-list walks |
| [`diff`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) | [`Diff`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html) | tree↔tree, index↔tree, worktree↔index |

For the raw backend, use [`references().store()`](https://docs.rs/grit-lib/latest/grit_lib/refs/struct.References.html#method.store) (same as [`ref_store`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.ref_store)).

Larger subsystems use [`repo_handles`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/index.html):

| Method | Handle | Role |
| --- | --- | --- |
| `Repository::remotes` | `Remotes` | List/get remotes, `ls-remote`, fetch, push, push planning, fetch/push over a caller-supplied transport (`fetch_from` / `push_to`) |
| `Repository::worktrees` | `Worktrees` | List/add/remove/lock/unlock linked worktrees |
| `Repository::stash` | `RepositoryStash` | Stash list/push/apply/pop/drop/branch/clear (the one stash API) |
| `Repository::notes` | `RepositoryNotes` | Notes list/read/add/remove via `NotesRef` |
| `Repository::bundles` | `Bundles` | Bundle write/verify/list-heads/unbundle/fetch |
| `Repository::snapshot_checkouts` | `SnapshotCheckouts` | Snapshot checkouts: make and project snapshots (server), refresh and check in (checkout). Only with the `unstable-hosting` feature, which is outside the semver promise |

Transport options, the stash identity, and notes authors and committers are passed in as arguments on those methods (no hidden wall-clock reads in the handle layer).

## Identity

Author, committer, and stash identities are typed [`Signature`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html) values (name, email, and an `OffsetDateTime`), not pre-formatted strings. [`Repository::identity`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.identity) resolves the one Git would record for an [`IdentRole`](https://docs.rs/grit-lib/latest/grit_lib/config/ident_resolve/enum.IdentRole.html) at a timestamp: it honours `GIT_AUTHOR_*` / `GIT_COMMITTER_*` (including the `*_DATE` overrides) from the handle's environment and `author.*`, `committer.*` and `user.*` config, and fails with [`CommitError::Identity`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.CommitError.html#variant.Identity) (a typed `IdentityError`) when no identity is configured or a date override is not a date Git accepts. The same resolution without a repository is [`resolve_signature_with`](https://docs.rs/grit-lib/latest/grit_lib/config/ident_resolve/fn.resolve_signature_with.html).

Use [`CommitRequest::new`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitRequest.html#method.new) for the message, then set public fields such as `author`. `CommitRequest` and `ContinueOptions` (merge `--continue`) take `Option<Signature>`, where `None` means the repository's identity for that role (for example, leave `committer` unset and `create_commit` uses the handle's committer identity); `RewriteOptions`, `StashPushOptions` and `NotesWriteOptions` take a `Signature`. Build one by hand with [`Signature::new`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html#method.new), parse a full `Name <email> <unix> <±HHMM>` header line with `str::parse`, or stamp a `--author`-style contact with [`AuthorContact::signature`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.AuthorContact.html#method.signature). Reflog entries use [`resolve_loose_committer_identity_with`](https://docs.rs/grit-lib/latest/grit_lib/config/ident_resolve/fn.resolve_loose_committer_identity_with.html), which never fails. [`Repository::identity_now`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.identity_now) gives the handle's clock (its reference time when one was set) in its `TZ`.

```rust
//! Resolve author identity and build a [`CommitRequest`].
//!
//! Source for the library guide "Repository" page Identity section (included in the docs site).

use std::ffi::OsString;

use grit_lib::config::environment::{Environment, RepositoryOptions};
use grit_lib::config::ident_resolve::IdentRole;
use grit_lib::error::Error;
use grit_lib::porcelain::commit::CommitRequest;
use grit_lib::repo::{InitOptions, Repository};

fn main() -> Result<(), Error> {
    let base = tempfile::tempdir().map_err(Error::Io)?;
    let root = base.path().join("repo");

    let env = Environment::from_vars(
        [
            ("GIT_AUTHOR_NAME", OsString::from("Ada Lovelace")),
            ("GIT_AUTHOR_EMAIL", OsString::from("ada@example.com")),
            ("GIT_COMMITTER_NAME", OsString::from("Committer Example")),
            (
                "GIT_COMMITTER_EMAIL",
                OsString::from("committer@example.com"),
            ),
        ]
        .into_iter()
        .map(|(k, v)| (OsString::from(k), v)),
        root.clone(),
    );

    let (repo, _) = Repository::init(
        &root,
        &InitOptions::new()
            .with_initial_branch("main")
            .with_repository_options(RepositoryOptions::with_environment(env)),
    )?;

    let author = repo.identity(IdentRole::Author, repo.identity_now())?;
    let mut request = CommitRequest::new("first\n");
    request.author = Some(author);
    // committer left None — create_commit uses the repository committer identity

    if let Some(author) = &request.author {
        println!("author={}", author.name);
    }

    Ok(())
}
```

## Errors

Library operations return `grit_lib::error::Result`. The top-level [`Error`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html) enum groups failures by area; repository layout, discovery, init, and embedding checks are [`Error::Repository`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Repository) wrapping [`RepositoryError`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html). Match on the inner variant in application code; the `grit` CLI maps them to exit codes and messages separately.

[`RepositoryError::NotARepository`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.NotARepository) carries a [`NotARepositoryReason`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.NotARepositoryReason.html): `NoRepositoryAt` when there is simply no repository at or above the path, or a gitfile problem (`GitfileNotRegularFile`, `GitfileMissingGitdir`, `GitfileUnreadable`) naming the `.git` entry. Discovery stops at a malformed gitfile instead of searching parent directories, as Git does, so treat the gitfile reasons as errors to report rather than "not in a repository". Other common [`RepositoryError`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html) variants include `DubiousOwnership` (`safe.directory`), `UnsupportedRepositoryFormatVersion`, `RequiresWorkTree`, `GitDirPathIo` (typed [`PathIoError`](https://docs.rs/grit-lib/latest/grit_lib/error/struct.PathIoError.html)), `ObjectFormatMismatch`, and init refusals such as `InitObjectFormatChange`.

## Example

The program below discovers a repository (or opens `.git` in the current directory), prints paths, and reads `user.name` from config:

```rust
//! Open and discover repositories; load config from the git directory.
//!
//! Source for the library guide "Repository" page (included in the docs site).

use grit_lib::config::environment::{Environment, RepositoryOptions};
use grit_lib::error::Error;
use grit_lib::repo::{Repository, RepositoryError};

fn main() -> Result<(), Error> {
    let cwd = std::env::current_dir().map_err(Error::Io)?;
    let env = Environment::from_vars(std::env::vars_os(), cwd.clone());
    let options = RepositoryOptions::with_environment(env.clone());

    let repo = match Repository::discover(None, &options) {
        Ok(r) => r,
        Err(Error::Repository(RepositoryError::NotARepository(_))) => {
            let git_dir = cwd.join(".git");
            Repository::open(&git_dir, &options.clone().with_work_tree(&cwd))?
        }
        Err(err) => return Err(err),
    };

    println!("git_dir={}", repo.git_dir().display());
    if let Some(wt) = &repo.work_tree() {
        println!("work_tree={}", wt.display());
    } else {
        println!("work_tree=<bare>");
    }

    let name = repo.config().get("user.name")?.unwrap_or_default();
    if !name.is_empty() {
        println!("user.name={name}");
    }

    Ok(())
}
```

Run from any Git checkout:

```bash
cargo run --bin guide_repository
```
