grit
CLILibrary
HEAD → docs/library/repository
Library guide / RepositoryMarkdown

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 is the main handle for grit-lib. Use Repository::git_dir, Repository::work_tree, and Repository::odb for paths and the object store; discovery provenance is available through DiscoveryInfo via Repository::discovery_info. The Environment used to open the handle is returned by Repository::environment.

Environment

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

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 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, or snapshot the variables you care about once and pass them through RepositoryOptions::with_environment, then call Repository::discover or Repository::open. RepositoryOptions::empty is for hermetic use such as tests.

Create new repositories with Repository::init and InitOptions; the call returns (Repository, InitOutcome) so callers can read what was written on disk (for example the initial branch name). Pass RepositoryOptions through InitOptions::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 leaves the handle hermetic, like RepositoryOptions::empty. Custom object and ref backends use RepositoryOptions::with_object_store (read layers through RepositoryOptions::with_odb_builder) and RepositoryOptions::with_ref_store, with Repository::init (which then creates no objects/ or refs/ for them; see Object stores), Repository::open or Repository::discover.

ConfigSet::load 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 returns a Config handle backed by RepoCaches (config cascade, gitattributes stacks, filter-process drivers, precompose flags, and related state). Call Config::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 stored on the repository (via RepositoryOptions::command_runner). The default is SystemCommandRunner, which is the only non-test code path that calls std::process::Command. Tests and embedders can install RecordingRunner or a custom runner to assert argv, environment, and stdin without executing real programs. Hook failures surface as HookError; shell filter subprocess failures use FilterError. When a filter.<driver>.required filter fails, staging, status and checkout return WorktreeError::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 when you have a working directory and want Git-style upward search. Call Repository::open when you already know the git directory; set RepositoryOptions::work_tree for non-bare layouts, RepositoryOptions::for_serving for smart-HTTP paths, and RepositoryOptions::without_format_validation when discovery must open before format checks.

After a handle is open, Repository::discovery_info returns DiscoveryInfo (whether discovery started from an explicit git directory, the discovery root, and related metadata). RepositoryLocation 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 (OwnershipCheck). The default SystemOwnershipCheck matches Git: owned repositories open immediately; foreign-owned paths require safe.directory. Embedders and tests install a custom check with RepositoryOptions::with_ownership_check (for example one that sets 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 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). 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 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 Objects read/write/contains for the ODB
references References resolve, list, update refs; read reflog
reflogs RepositoryReflogs list reflog refs, show/delete/expire entries
index IndexFile load/write the index
config Config merged get; local set + reload
revwalk RevWalk rev-parse specs; rev-list walks
diff Diff tree↔tree, index↔tree, worktree↔index

For the raw backend, use references().store() (same as ref_store).

Larger subsystems use repo_handles:

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

Errors

Library operations return grit_lib::error::Result. The top-level Error enum groups failures by area; repository layout, discovery, init, and embedding checks are Error::Repository wrapping RepositoryError. Match on the inner variant in application code; the grit CLI maps them to exit codes and messages separately.

RepositoryError::NotARepository carries a NotARepositoryReason: 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 variants include DubiousOwnership (safe.directory), UnsupportedRepositoryFormatVersion, RequiresWorkTree, GitDirPathIo (typed PathIoError), ObjectFormatMismatch, and init refusals such as InitObjectFormatChange.