# Index

> Load the staging index, stage paths with porcelain add, and write a tree object from staged entries.

The Git index (staging area) lives in `Index`. Open a `Repository`, then use `IndexFile` via `Repository::index` (`load` / `write`). Index extensions (sparse checkout, split index, untracked cache) live under the [`index`](https://docs.rs/grit-lib/latest/grit_lib/index/index.html) domain; working-tree helpers are under [`worktree`](https://docs.rs/grit-lib/latest/grit_lib/worktree/index.html). See [API layout](https://grit-scm.com/docs/library/api-layout/index.md).

See also the [Repository](https://grit-scm.com/docs/library/repository/index.md) and [Objects](https://grit-scm.com/docs/library/objects/index.md) pages for opening repos and writing objects. Other library topics: [Refs](https://grit-scm.com/docs/library/refs/index.md), [Diff](https://grit-scm.com/docs/library/diff/index.md).

## Reading the index

[`IndexFile::load`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexFile.html#method.load) reads the index (`GIT_INDEX_FILE` or `.git/index`), resolves a split index, and by default expands every sparse-directory placeholder (full in-memory materialization). [`IndexLoadOptions`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexLoadOptions.html) selects another file (`with_path`), keeps placeholders for read-mostly work such as `status` and `diff` on cone sparse-index checkouts (`with_sparse(SparseIndexLoad::Preserve)`), or sets the entry-loading thread policy (`with_parse_context`). Entries are [`IndexEntry`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexEntry.html) values with path, mode, object id, and stage; build one in memory with [`IndexEntry::new`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexEntry.html#method.new) (stage 0, zeroed stat data) and [`with_stage`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexEntry.html#method.with_stage) for a conflict stage.

```rust
use grit_lib::index::{IndexLoadOptions, IndexWriteOptions, SparseIndexLoad};

let mut index = repo.index().load(&IndexLoadOptions::default())?;
// ... edit entries ...
repo.index().write(&mut index, &IndexWriteOptions::default())?;

let compact = repo
    .index()
    .load(&IndexLoadOptions::default().with_sparse(SparseIndexLoad::Preserve))?;
```

[`IndexFile::write`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexFile.html#method.write) collapses skip-worktree subtrees back into sparse-directory entries when `index.sparse` is on, writes a split index when [`IndexWriteOptions::split`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexWriteOptions.html) or `core.splitIndex` asks for one, and runs the `post-index-change` hook. To parse index bytes you already have, use [`Index::parse`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.Index.html#method.parse) with [`IndexParseOptions`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexParseOptions.html) (hash algorithm, config for EOIE/IEOT, source path for errors, thread policy); [`Index::empty_for`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.Index.html#method.empty_for) makes an empty index whose version follows `index.version` and `feature.manyFiles`.

## Staging paths

`porcelain::add::stage` compares the index to the work tree once, hashes changed blobs, and writes the index back. Pass `StageOptions` for pathspecs and `StageMode` (`All` vs `Update`). Long-running staging reports through a `ProgressSink`; examples use `NullProgress` when no UI is needed.

The `grit add` command is a thin wrapper around this API.

`StageOptions::pathspecs` are work-tree-relative. Prefer [`Repository::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.pathspec) with [`PathspecOptions`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.PathspecOptions.html) to resolve argv and `--pathspec-from-file` input in one step ([`Pathspec::specs`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html#method.specs) for matching, [`Pathspec::iter`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html#method.iter) for display). The resolved [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html) carries both display sources and normalized specs ([`Pathspec::iter`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html#method.iter)). Resolution applies the current-directory prefix and, on filesystems that alias NFD/NFC spellings (macOS with `core.precomposeunicode`), NFC-normalizes paths. That decision is cached on the `Repository`, so passing hundreds of literal paths costs no config reload per path, and literal pathspecs are matched against the index with hash lookups on every platform.

[`StatusOptions::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusOptions.html#structfield.pathspec) uses the same [`Pathspec`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html) type; `grit status` resolves CLI path arguments through [`Repository::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.pathspec).

## Worktree file modes

Some checkouts cannot show every mode Git records. With `core.filemode=false` the executable bit on disk means nothing, and with `core.symlinks=false` (the Windows default when symlinks need admin rights) a symlink is checked out as a plain file holding the link target. [`WorktreeModePolicy`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.WorktreeModePolicy.html) reads both settings with `from_config` and maps an `lstat` mode onto the mode already in the index: `index_mode_for_worktree` keeps a recorded `120000` for a plain file when symlinks are disabled, and keeps a recorded `100644`/`100755` when the filemode is not trusted. Staging, `commit`, `status` and worktree diffs all go through it, so an untouched link stays a link and an edited one is staged as a new link target, the same as Git.

## Sparse checkout

[`SparseCheckout::load`](https://docs.rs/grit-lib/latest/grit_lib/index/sparse_checkout/struct.SparseCheckout.html#method.load) compiles the repository's sparse-checkout definition (`core.sparseCheckout`, `core.sparseCheckoutCone` and `info/sparse-checkout`, cone or non-cone) once, and returns `None` when sparse checkout is off. [`SparseCheckout::includes`](https://docs.rs/grit-lib/latest/grit_lib/index/sparse_checkout/struct.SparseCheckout.html#method.includes) answers whether a path belongs in the work tree.

[`IndexFile::apply_sparse_checkout`](https://docs.rs/grit-lib/latest/grit_lib/index/struct.IndexFile.html#method.apply_sparse_checkout) marks the excluded stage-0 entries of an index built from a tree as skip-worktree, as Git does after `read-tree` or a branch checkout.

Every operation that updates the work tree from a tree consults it: `reset --hard` and `--mixed`, `switch`, `merge`, `pull` (merge and rebase), stash and the history engine. A path outside the definition that is skip-worktree (or new to the index) gets an index row with the `skip-worktree` bit and nothing is written to disk, the same as `git`. Conflicted paths are written out with conflict markers, also like `git`. When `index.sparse` is on, the index is collapsed back into sparse-directory entries when it is written. [`SparseCheckout::carry_skip_worktree`](https://docs.rs/grit-lib/latest/grit_lib/index/sparse_checkout/struct.SparseCheckout.html#method.carry_skip_worktree) keeps the bits on an index rebuilt from a tree without touching the work tree.

## Writing a tree from the index

[`write_tree_from_index`](https://docs.rs/grit-lib/latest/grit_lib/index/write_tree/fn.write_tree_from_index.html) builds a tree object from stage-0 entries (respecting the optional path prefix). It returns the root [`ObjectId`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectId.html). When the index cache-tree extension is valid, grit reuses cached subtree oids for speed; otherwise it walks entries and writes new tree objects through [`Odb`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html).

## Errors

Index load, write, extension parsing, and write-tree failures return [`IndexError`](https://docs.rs/grit-lib/latest/grit_lib/index/error/enum.IndexError.html) (wrapped as [`Error::Index`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Index) at the repository boundary). Match on the enum, not message text:

| Variant | When |
| --- | --- |
| `Corrupt` | Bad header, unsupported version, truncated bytes, checksum mismatch, or malformed entries/extensions (`IndexCorruptReason` pinpoints the site). |
| `Unmerged` | Conflict stages remain; commit or write-tree needs a clean stage-0 index. |
| `PathPrefixConflict` | Two paths disagree on whether a prefix is a file or directory. |
| `FsmonitorExtension*` | The `FSMN` extension is truncated, has an unknown version, or carries an invalid EWAH bitmap. |
| `CacheTreeCorrupt` | Cache-tree metadata does not match index entries. |
| `LockHeld` | Another process holds `index.lock` (also surfaced as top-level [`Error::LockHeld`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.LockHeld)). |
| `PathIo` | Filesystem I/O on the index path. |
| `SplitIndex` | Split-index link/read/write failed. |
| `Chmod` | Mode change rejected (unmerged path, non-regular file, invalid mode). |
| `WriteTree` | Structured write-tree / cache-tree rebuild failure. |

Stable JSON `kind` slugs (`index_error`, `index_unmerged`, `cache_tree_corrupt`, …) come from [`IndexError::kind_name`](https://docs.rs/grit-lib/latest/grit_lib/index/error/enum.IndexError.html#method.kind_name). See the [errors](https://grit-scm.com/docs/library/errors/index.md) overview for the cross-area map.

## Example

This program loads the index, stages new or changed paths, and prints the tree oid grit would commit:

```rust
//! Read the index, stage paths, and write a tree from staged entries.
//!
//! Source for the library guide "Index" page (included in the docs site).

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::index::write_tree::write_tree_from_index;
use grit_lib::porcelain::add::StageOptions;
use grit_lib::progress::NullProgress;
use grit_lib::repo::{InitOptions, Repository};
use std::fs;
use std::path::{Path, PathBuf};

fn open_repo(root: &Path) -> Result<Repository, grit_lib::error::Error> {
    let git_dir = if root.join(".git").is_dir() {
        root.join(".git")
    } else {
        root.to_path_buf()
    };
    let work_tree = if root.join(".git").is_dir() {
        Some(root)
    } else {
        None
    };
    let mut opts = RepositoryOptions::empty();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Repository::open(&git_dir, &opts)
}

fn main() -> Result<(), grit_lib::error::Error> {
    let mut temp_guard = None;
    let repo = if let Some(root) = std::env::args().nth(1).map(PathBuf::from) {
        open_repo(&root)?
    } else {
        let temp = tempfile::tempdir().map_err(grit_lib::error::Error::Io)?;
        Repository::init(
            temp.path(),
            &InitOptions::new()
                .with_initial_branch("main")
                .with_ref_storage(grit_lib::refs::ref_storage::RefStorageFormat::Files),
        )?;
        let path = temp.path().join("hello.txt");
        fs::write(&path, b"staged from the library guide\n").map_err(grit_lib::error::Error::Io)?;
        let opened = open_repo(temp.path())?;
        temp_guard = Some(temp);
        opened
    };
    let _keep = temp_guard;

    let index = repo
        .index()
        .load(&grit_lib::index::IndexLoadOptions::default())?;
    println!("index_entries={}", index.entries().len());

    let outcome = repo.index().stage(
        &StageOptions::default(),
        &mut NullProgress,
        &grit_lib::progress::CancelToken::never(),
    )?;
    println!(
        "staged added={} modified={} removed={}",
        outcome.added.len(),
        outcome.modified.len(),
        outcome.removed.len()
    );

    let index = repo
        .index()
        .load(&grit_lib::index::IndexLoadOptions::default())?;
    let tree_oid = write_tree_from_index(repo.odb(), &index, "")?;
    println!("tree_oid={}", tree_oid.to_hex());

    Ok(())
}
```

With a repository path, compare the printed tree to Git:

```bash
cargo run --bin guide_index /path/to/repo
git -C /path/to/repo write-tree
git -C /path/to/repo fsck --strict
```

Without arguments the binary uses a temporary repository (useful for `cargo run`, not for fsck demos).
