# Embedding grit-lib

> Run multiple repositories in one process with explicit Environment, sinks, subprocess injection, and typed errors.

Grit is designed to be **linked into other Rust programs**, not only invoked as the `grit` CLI. The library avoids hidden process globals: discovery variables, config identity, subprocesses, warnings, and wall-clock references are supplied through explicit types at the boundary.

## Environment

[`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) holds Git discovery and configuration variables (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_CONFIG_*`, home paths, author/committer overrides, transport trace flags, and related fields). Construct it with:

- [`Environment::capture_process`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#method.capture_process) — an explicit snapshot of the calling process (`HOME`, `GIT_*`, Windows `ProgramFiles`, identity variables, …). This is what the `grit` CLI uses, and what a tool working on a user's repositories should use. Call it in your program, never from library code.
- [`Environment::from_vars`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#method.from_vars) — parse an iterator of `(key, value)` pairs plus an explicit working directory (no reads from `std::env` inside the library).
- [`Environment::empty`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#method.empty) — no variables at all (`cwd = "."`). There is no home directory, so the global `~/.gitconfig` is not read, and on Windows the Git for Windows system gitconfig cannot be found. On Unix `/etc/gitconfig` still loads unless you set `git_config_nosystem`.

Pass the same `Environment` into `Repository` (`discover` / `open`) and into `ConfigSet` loading.

### Matching `git` and `grit` on user repositories

System and global config decide much of what a repository operation does: `core.autocrlf` (Git for Windows sets it to `true` in its system config), `user.name` / `user.email`, `safe.directory`, `core.excludesFile`, credential helpers. A program that should give the same answers as `git` and `grit` on the user's machine opens repositories with [`RepositoryOptions::from_process`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.from_process):

```rust
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::repo::Repository;

let repo = Repository::discover(None, &RepositoryOptions::from_process())?;
```

With [`RepositoryOptions::empty`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.empty) none of that config applies. For example, on Windows `status` then reports CRLF files that `git status` calls clean as modified. Use `empty()` for hermetic work such as tests or a repository your program created itself. The examples on these pages that open your repository use `from_process()`; the ones that create a throwaway repository (`guide_embedding` below, and `guide_index`, `guide_objects` and `guide_replay_conflicts` when run without a path) stay on `empty()`, and `guide_embedding` sets its home directory and disables the system config explicitly.

Clones share the captured variable map, avoiding a copy of every inherited variable during
repository setup. Typed fields remain independent: changing or clearing an override on a
clone leaves the original snapshot unchanged. Untyped variables, including non-Unicode
values, remain available to subprocesses after the original snapshot is dropped.
Empty snapshots need no allocation for the captured map.

## RepositoryOptions

[`RepositoryOptions`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) bundles everything needed to open a repository besides paths:

| Field | Role |
| --- | --- |
| `environment` | Discovery/config/identity snapshot |
| `command_runner` | Injectable subprocess execution (hooks, filters, signing helpers) |
| `diagnostics` | `DiagnosticSink` for warnings and trace events |
| `network_trace` | When true, emit network trace events via the diagnostics sink |
| `reference_unix_time` | Wall clock for rev-parse date selectors (`@{yesterday}`, etc.) |
| `ownership_check` | Injectable [`OwnershipCheck`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/trait.OwnershipCheck.html) for `safe.directory` (default [`SystemOwnershipCheck`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/struct.SystemOwnershipCheck.html)) |

Construct options with one of the associated constructors, then chain the builder methods:

| Constructor | Environment |
| --- | --- |
| [`RepositoryOptions::from_process()`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.from_process) | Snapshot of the calling process, like `git` and `grit` |
| [`RepositoryOptions::with_environment(env)`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_environment) | An [`Environment`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) you built |
| [`RepositoryOptions::empty()`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.empty) | [`Environment::empty`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html#method.empty) |

`with_environment` takes the environment and returns new options, so write `RepositoryOptions::with_environment(env).with_command_runner(runner)`; `RepositoryOptions::empty().with_environment(env)` does not compile. Assign `diagnostics` (or call `with_diagnostics`) when you need a custom sink.

## DiagnosticSink and ProgressSink

Non-fatal conditions are `Warning` values delivered to a `DiagnosticSink`. The default is `NullDiagnostics`. Tests and embedders often use `CollectingDiagnostics` to assert warnings without parsing stderr.

Long-running work (status, staging and commit, stash, merge, rebase, checkout and switch, fetch, pack indexing) takes a [`ProgressSink`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html) and a [`CancelToken`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html). Pass [`NullProgress`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.NullProgress.html) and [`CancelToken::never`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html#method.never) when you don't want progress updates or interruption.

Share cancellation across threads or wire a UI stop button with [`CancelToken`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html): clone the token, call [`cancel`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html#method.cancel) from another thread, and pass `&token` anywhere a [`CancelToken`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html) is accepted today. Do not poll cancellation from a custom [`ProgressSink`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html); see [Progress and cancellation](https://grit-scm.com/docs/library/embedding/parallelism.md/index.md#progress-and-cancellation) for where a cancel lands. Progress is separate from diagnostics: progress reports throughput; diagnostics report Git-style warnings.

## CommandRunner

`CommandRunner` is the only production path that spawns OS processes from the library (`SystemCommandRunner`). Hooks, smudge/clean filters, credential helpers, and signing helpers build a `CommandSpec` and call `spawn`.

Shell commands use a `CommandSpec` whose program is `sh`. `SystemCommandRunner` runs that the way Git does: `/bin/sh` on Unix. On Windows it uses the `sh` of the Git for Windows install that owns the `git` on the child's `PATH` (`usr\bin`, then `bin`), then any `sh` on that `PATH`. Filters and helpers therefore work when only Git's `cmd` directory is on `PATH`.

For tests, [`RecordingRunner`](https://docs.rs/grit-lib/latest/grit_lib/command_runner/struct.RecordingRunner.html) records specs and returns scripted exit codes. Install it on [`RepositoryOptions`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html) before [`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).

## Typed errors

Library APIs return `grit_lib::error::Result`. Match on the umbrella's area variant and then the area enum's variant (`Error::Revision(RevisionError::Parse(..))`, `Error::Hook(..)`, `Error::Worktree(WorktreeError::Filter(..))`, …) instead of parsing `"fatal:"` strings. The CLI maps variants to exit codes and human messages in its own words.

Area enums, shared leaf types, JSON `kind` slugs, and migration rules are documented in [Typed errors](https://grit-scm.com/docs/library/embedding/docs/library/errors/index.md). The umbrella [`Error`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html) has one variant per area; [`Error::kind_name`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#method.kind_name) names the specific failure and [`Error::area`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#method.area) its area.

Common conditions use dedicated variants rather than message strings: bare or missing work tree → [`RepositoryError::RequiresWorkTree`](https://docs.rs/grit-lib/latest/grit_lib/repo/error/enum.RepositoryError.html#variant.RequiresWorkTree) (via [`Error::Repository`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Repository)); empty commit body → [`CommitError::EmptyCommitMessage`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/enum.CommitError.html#variant.EmptyCommitMessage) (via [`Error::Commit`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Commit)); path missing from a revision tree → [`RevParseError::PathNotInRevision`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_parse_error/enum.RevParseError.html#variant.PathNotInRevision); parent navigation past root → [`RevParseError::RevisionOutOfRange`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_parse_error/enum.RevParseError.html#variant.RevisionOutOfRange); pack deltas whose bases are in neither the pack nor the object database (a thin pack received without its bases) → [`ObjectError::UnresolvedDeltas`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.UnresolvedDeltas); a `.idx` whose trailing checksum is wrong, on reads that verify it → [`ObjectError::PackIndexChecksumMismatch`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.PackIndexChecksumMismatch).

## Code layout

Enable the `hot-text-layout` feature to have grit-lib's hot code path (the library, runtime and dependency functions its common operations run) placed contiguously in your binary:

```toml
[dependencies]
grit-lib = { version = "0.5", features = ["hot-text-layout"] }
```

A short operation then faults in a few contiguous code pages instead of windows scattered over the whole binary. `grit status` on 10,000 files drops from 14.2 to 11.5 MB of peak RSS with it, and nothing changes at run time. The feature acts only on `x86_64-unknown-linux-gnu`, where rustc links with LLD; elsewhere it does nothing. Set `GRIT_HOT_TEXT_LAYOUT=0` at build time if you link with another linker. See [Hot text layout](https://grit-scm.com/docs/library/benchmarking.md/index.md#hot-text-layout).

## Serializable results

Enable the `serde-models` feature to get `serde::Serialize` on the results a front end renders, so you don't write your own JSON types for them:

```toml
[dependencies]
grit-lib = { version = "0.5", features = ["serde-models"] }
```

The feature covers [`StatusModel`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusModel.html) (including its paused [`Operation`](https://docs.rs/grit-lib/latest/grit_lib/state/struct.Operation.html), state flags and conflict kinds; the loaded index is not serialized), [`DiffEntry`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffEntry.html), [`LoadedCommit`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/log/struct.LoadedCommit.html), porcelain outcomes for merge ([`IntegrateBranchOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/merge/enum.IntegrateBranchOutcome.html)), pull ([`PullOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/pull/struct.PullOutcome.html)), clone ([`CloneOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/clone/struct.CloneOutcome.html); the open [`Repository`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html) is omitted), checkout ([`CheckoutOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/checkout/struct.CheckoutOutcome.html)), stage/clean/restore/remove/move ([`StageOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/add/struct.StageOutcome.html), [`CleanOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/clean/struct.CleanOutcome.html), [`RestoreOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/restore/struct.RestoreOutcome.html), [`RemoveOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/paths/struct.RemoveOutcome.html), [`MoveOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/paths/struct.MoveOutcome.html)), tag create ([`CreateTagOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/tag/struct.CreateTagOutcome.html); tree-sha256 detail is omitted), stash push ([`StashPushResult`](https://docs.rs/grit-lib/latest/grit_lib/stash/struct.StashPushResult.html)), commit/switch/reset, branch listing ([`BranchList`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/branch/struct.BranchList.html), [`BranchSummary`](https://docs.rs/grit-lib/latest/grit_lib/refs/branch_tracking/struct.BranchSummary.html), [`TargetComparison`](https://docs.rs/grit-lib/latest/grit_lib/refs/branch_tracking/struct.TargetComparison.html)), stash apply/list, fetch/push, history rewrites and rebase ([`CommitOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitOutcome.html), [`SwitchOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/switch/struct.SwitchOutcome.html), [`ResetOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/reset/struct.ResetOutcome.html), [`StashEntry`](https://docs.rs/grit-lib/latest/grit_lib/stash/struct.StashEntry.html), [`StashApplyOutcome`](https://docs.rs/grit-lib/latest/grit_lib/stash/struct.StashApplyOutcome.html), [`FetchOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.FetchOutcome.html), [`PushOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/transfer/struct.PushOutcome.html), [`RewritePlan`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/struct.RewritePlan.html), [`RebaseOutcome`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/enum.RebaseOutcome.html), [`RebasePlan`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/enum.RebasePlan.html), [`UndoOutcome`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/history/struct.UndoOutcome.html)), refs and notes ([`RefListing`](https://docs.rs/grit-lib/latest/grit_lib/refs/listing/struct.RefListing.html), [`ReflogEntry`](https://docs.rs/grit-lib/latest/grit_lib/refs/reflog/struct.ReflogEntry.html), [`NoteListing`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.NoteListing.html)), index and objects ([`IndexEntry`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexEntry.html), [`TreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html), [`ObjectInfo`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectInfo.html)), diff depth ([`FileDiff`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileDiff.html), [`DiffStat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html) with [`FileStat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileStat.html) rows), maintenance ([`GcStats`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.GcStats.html)), rev-list ([`RevListResult`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListResult.html); internal walk buffers are omitted), smart HTTP serve ([`UploadOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.UploadOutcome.html), [`ReceiveOutcome`](https://docs.rs/grit-lib/latest/grit_lib/remote/serve/struct.ReceiveOutcome.html)), bundles ([`UnbundleOutcome`](https://docs.rs/grit-lib/latest/grit_lib/bundle/struct.UnbundleOutcome.html)), config ([`ConfigEntry`](https://docs.rs/grit-lib/latest/grit_lib/config/struct.ConfigEntry.html)), plus blame ([`BlameResult`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameResult.html)), describe ([`DescribedCommit`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.DescribedCommit.html)), tag list ([`TagSummary`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/tag/struct.TagSummary.html), [`TagList`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/tag/enum.TagList.html)), and worktree list ([`WorktreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/worktree/struct.WorktreeEntry.html)). The shapes:

| Type | JSON |
| --- | --- |
| [`ObjectId`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectId.html), [`ChangeId`](https://docs.rs/grit-lib/latest/grit_lib/change_id/struct.ChangeId.html) | hex string |
| [`FileMode`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.FileMode.html) | octal string such as `"100644"`; `"000000"` for the missing side of an add or delete |
| [`IndexEntry`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexEntry.html) | `path` as UTF-8 text (lossy when needed); `mode` as a [`FileMode`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.FileMode.html) octal string |
| [`TreeEntry`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.TreeEntry.html) | `name` as UTF-8 text; `mode` as Git's minimal octal (`"40000"` for trees) |
| [`BranchSummary`](https://docs.rs/grit-lib/latest/grit_lib/refs/branch_tracking/struct.BranchSummary.html) | `committer_time` as RFC 3339 when present |
| [`DiffStat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.DiffStat.html) | `files` ([`FileStat`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.FileStat.html) rows) and `totals` |
| [`HunkId`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.HunkId.html) | 12 lowercase hex characters |
| [`Signature`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html), [`CommitAuthorInfo`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitAuthorInfo.html) | `{"name", "email", "date"}`, with `date` in RFC 3339 keeping the recorded offset |
| [`Error`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html) | Always `kind`, `message`, and additive `area` ([`Error::area`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#method.area); not a script contract). Selected variants also expose structured fields: `LockHeld` → `path`, optional `holder` `{pid, running}`; `WouldOverwrite` → `reason`, `paths`; `StashCouldNotRestoreUntracked` → `path`; `DirtyWorktree` → `operation`, `paths`; `UnmergedConflictMarkers` → `paths` |
| enums | snake_case variant names (`"type_changed"`, `"merge"`); hook names use Git's spelling (`"pre-commit"`) |

`LoadedCommit` holds typed author and committer signatures. A commit whose identity line has a malformed date still loads, with the Unix epoch as its date, the way `git log` shows it ([`Signature::from_header_lossy`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html#method.from_header_lossy)).

[`CommitOutcome`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitOutcome.html) includes the full commit `message`, `author`, and `committer` ([`CommitAuthorInfo`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitAuthorInfo.html) serializes like [`Signature`](https://docs.rs/grit-lib/latest/grit_lib/ident/struct.Signature.html)). [`CommitFile`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/commit/struct.CommitFile.html) status uses snake_case enum names (`modified`, …) in JSON; the `grit commit --json` command still prints Git's single-letter codes and adds scope, subject, and dry-run fields the library outcome does not carry. The same pattern applies to blame, describe, tag list, and worktree list: CLI `--json` is a thin view over these library models (extra fields such as `file`/`rev` on blame, flattened branch/head on worktree list), not a byte-identical dump of `serde_json::to_value` on the library type.

## Concurrency

Two or more `Repository` handles may be used from different threads in one process when each handle is opened with its **own** `Environment`, `RepositoryOptions`, diagnostics sink, and command runner. Repository-scoped caches (config, attributes, pack read caches) do not leak between handles.

Object writes are safe to race. Every loose object is staged in its own uniquely named `objects/xx/tmp_obj_*` file and renamed into place, so handles, threads or processes writing the same object at once all get its id back (whichever rename lands first publishes it, the same as Git). Pack installs are safe to race too, so parallel fetches into one repository all succeed: [`install_pack_path`](https://docs.rs/grit-lib/latest/grit_lib/objects/index_pack/fn.install_pack_path.html) stages each install in its own directory, and fetches from a local remote hard-link or copy its packs through a private temp file. Both publish without replacing a `.pack` or `.idx` that is already there under the same content-addressed name (the `.idx` always lands after its `.pack`), and a failed or cancelled install removes only its private staging files, never a published `.pack` or `.idx` another writer may already rely on. Ref updates such as adding a note are compare-and-swap: when two writers race, one wins and the other gets a typed ref-store error instead of losing the first update.

Integration coverage: `grit-lib/tests/concurrent_repos.rs` runs parallel commit loops and a fetch/merge/notes scenario with isolated config and sinks; `grit-lib/tests/loose_write_concurrent_issue_1875.rs` races identical small and large blob writes from separate handles and checks the result with `git fsck --strict`; `grit-lib/tests/index_pack_parallel.rs` installs one pack from several threads into one repository and checks it the same way.

## Example

```rust
//! Open two repositories in one process with isolated environments and sinks.
//!
//! Source for the library guide "Embedding" page (included in the docs site).

use std::sync::Arc;

use grit_lib::command_runner::RecordingRunner;
use grit_lib::config::environment::{Environment, RepositoryOptions};
use grit_lib::diagnostics::{CollectingDiagnostics, DiagnosticSink};
use grit_lib::error::Error;
use grit_lib::repo::{InitOptions, Repository};

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

    let open_named =
        |name: &str, email: &str| -> Result<(Repository, Arc<CollectingDiagnostics>), Error> {
            let root = base.path().join(name);
            let (_repo, _) = Repository::init(
                &root,
                &InitOptions::new()
                    .with_initial_branch("main")
                    .with_ref_storage(grit_lib::refs::ref_storage::RefStorageFormat::Files),
            )?;

            let home = base.path().join(format!("home-{name}"));
            std::fs::create_dir_all(&home).map_err(Error::Io)?;
            let global = home.join(".gitconfig");
            std::fs::write(
                &global,
                format!("[user]\n\tname = {name}\n\temail = {email}\n"),
            )
            .map_err(Error::Io)?;

            let mut env = Environment::empty();
            env.cwd = root.clone();
            env.home = Some(home.into());
            env.git_config_global = Some(global.to_string_lossy().into_owned());
            env.git_config_nosystem = Some("true".into());
            env.git_config_system = Some("/dev/null".into());

            let diagnostics = Arc::new(CollectingDiagnostics::new());
            let sink: Arc<dyn DiagnosticSink + Send + Sync> = diagnostics.clone();
            let runner = RecordingRunner::always_success();
            let mut options = RepositoryOptions::with_environment(env).with_command_runner(runner);
            options.diagnostics = sink;

            let git_dir = root.join(".git");
            let repo = Repository::open(&git_dir, &options.clone().with_work_tree(&root))?;
            Ok((repo, diagnostics))
        };

    let (repo_a, sink_a) = open_named("alpha", "a@example.com")?;
    let (repo_b, sink_b) = open_named("beta", "b@example.com")?;

    let name_a = repo_a
        .config()
        .snapshot()?
        .get("user.name")?
        .unwrap_or_default();
    let name_b = repo_b
        .config()
        .snapshot()?
        .get("user.name")?
        .unwrap_or_default();
    println!("alpha user.name={name_a}");
    println!("beta user.name={name_b}");
    println!("alpha warnings={}", sink_a.warnings().len());
    println!("beta warnings={}", sink_b.warnings().len());

    Ok(())
}
```

Build and run:

```bash
cargo run -p grit-examples --bin guide_embedding
```

## Blame and repository-relative paths

[`Diff::blame`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.blame),
[`compute_blame`](https://docs.rs/grit-lib/latest/grit_lib/blame/fn.compute_blame.html), and
[`Diff::resolve_blame_line_range`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.resolve_blame_line_range)
take **repository-relative** paths. Like [`RevWalk::commits`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.commits) and [`RevWalk::describe`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.describe), they accept a [`ProgressSink`](https://docs.rs/grit-lib/latest/grit_lib/progress/trait.ProgressSink.html) and [`CancelToken`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html) after their options (use [`NullProgress`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.NullProgress.html) and [`CancelToken::never`](https://docs.rs/grit-lib/latest/grit_lib/progress/struct.CancelToken.html#method.never) when unused): the same string names the same file no matter
where the host process is running. Pass status paths unchanged. For a raw byte
path, build the input with `repo_relpath::storage_string`. Non-UTF-8 paths and
names beginning with the reserved `grit+pathhex:` prefix are escaped. Absolute
paths under the work tree and `./` / `../` segments normalize against the
work-tree root. To turn command-line operands into that form (cwd-relative, like
`git blame`), resolve each path with
[`Repository::resolve_worktree_pathspec`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.resolve_worktree_pathspec)
using [`Repository::pathspec_argv_prefix`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.pathspec_argv_prefix)
before calling blame APIs.

Every blame `original_path`, including hunks and rename/copy origins, uses that
same storage representation. Recover its exact bytes with
`repo_relpath::storage_bytes`. Decode once:
a literal filename that itself resembles an encoded path is a separate file.
Line ranges and Git-written changed-path Bloom filters use the decoded path too.

### Blaming uncommitted content

By default `repo.diff().blame` blames the file as committed at
[`BlameOptions::start`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameOptions.html#structfield.start) (or
`HEAD`). Set
[`BlameOptions::final_source`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameOptions.html#structfield.final_source)
to [`BlameFinalSource::Worktree`](https://docs.rs/grit-lib/latest/grit_lib/blame/enum.BlameFinalSource.html#variant.Worktree)
to blame the working-tree file, or to
[`BlameFinalSource::Contents`](https://docs.rs/grit-lib/latest/grit_lib/blame/enum.BlameFinalSource.html#variant.Contents)
with an editor buffer's bytes. The content is blamed as a commit on top of the
start revision (plus any `MERGE_HEAD` commits), so returned line numbers match
the buffer. Lines that exist only in that content have
[`BlameAttributedLine::not_committed`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameAttributedLine.html#structfield.not_committed)
set and the null object id as `commit`; their
[`BlameCommitInfo`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameCommitInfo.html) carries
[`BlameOptions::now`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameOptions.html#structfield.now) as the author
time and the placeholder identity Git reports (`Not Committed Yet`, or
`External file (--contents)` for a buffer; see
[`BlameFinalSource::uncommitted_author_name`](https://docs.rs/grit-lib/latest/grit_lib/blame/enum.BlameFinalSource.html#method.uncommitted_author_name)).
[`BlameResult::hunks`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameResult.html#method.hunks) groups the
lines like `git blame --porcelain`; each
[`BlameHunk`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameHunk.html) flags `not_committed` and
hands back its own lines through
[`BlameResult::hunk_lines`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameResult.html#method.hunk_lines). Resolve `-L` specs against the same
text with
[`Diff::resolve_blame_line_range_with_options`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Diff.html#method.resolve_blame_line_range_with_options).
Nothing is written to the object database.

```rust
use grit_lib::blame::{BlameFinalSource, BlameOptions};
use grit_lib::progress::{CancelToken, NullProgress};

# fn editor(repo: &grit_lib::repo::Repository, buffer: Vec<u8>) -> grit_lib::error::Result<()> {
let result = repo.diff().blame(
    "src/main.rs",
    &BlameOptions::default().with_final_source(BlameFinalSource::Contents(buffer)),
    &mut NullProgress,
    &CancelToken::never(),
)?;
for line in result.lines.iter().filter(|line| line.not_committed) {
    println!("unsaved or uncommitted: {}", line.content);
}
# Ok(())
# }
```
