# Bundle

> Offline pack bundles — create, verify, list heads, unbundle, and fetch.

Git bundle files combine a header and thin pack for offline transfer. The [`bundle`](https://docs.rs/grit-lib/latest/grit_lib/bundle/index.html) domain implements read/write/verify compatible with system `git bundle`. [`Repository::bundles`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.bundles) returns [`RepositoryBundles`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryBundles.html) scoped to one open repository. Every operation has one method; long-running ones take a trailing `&mut dyn ProgressSink` and `&CancelToken` (pass `NullProgress` and `CancelToken::never()` when you need neither).

| Method | Role |
| --- | --- |
| `write` | Write a bundle file from `BundleSpec` tips (atomic replace via `*.bundle.part`); returns the ref count |
| `write_from_revs` | Same, from `bundle create`-style revision arguments (`BundleCreateOptions`: tips, `A..B`, `--all`) |
| `write_to` | Stream a bundle (header, then pack) into any `Write` |
| `plan_create` / `plan_create_from_revs` | Dry run: the refs, prerequisites and object count a write would produce |
| `verify` | Check prerequisites and connectivity (`BundleVerifyReport`) |
| `list_heads` | Parse ref tips from the header |
| `plan_unbundle` | Dry run of `unbundle`: verification and the ref updates it implies |
| `unbundle` | Ingest the pack without updating refs |
| `fetch` | `git fetch` from a bundle file: verify, ingest, and update refs per `FetchOptions` |

Failed or cancelled `write` calls leave an existing destination file unchanged. Grit writes to a sibling `path.bundle.part` and renames onto `path` only after the pack stream succeeds. Missing objects surface as [`ObjectError::NotFound`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.ObjectError.html#variant.NotFound) under [`Error::Object`](https://docs.rs/grit-lib/latest/grit_lib/error/enum.Error.html#variant.Object), not a generic I/O string.

With a files-backed repository `unbundle` installs the pack under `objects/pack/`. With a custom primary object store it writes every object of the pack into that store instead (see [Object stores](https://grit-scm.com/docs/library/bundle/object-stores.md/index.md#receiving-packs-into-a-custom-store)).

[`write_to`](https://docs.rs/grit-lib/latest/grit_lib/repo_handles/struct.RepositoryBundles.html#method.write_to) streams the pack into the `Write` you pass (wrap files in a `BufWriter`), so the whole pack is never held in memory. When the repository has local packs, deltas and whole objects already stored there are copied verbatim instead of being recomputed, so bundling a packed repository costs about as much as copying its pack.

Cloning from a bundle path goes through the normal clone API; network transport is covered on the [Network](https://grit-scm.com/docs/library/network/index.md) page.

## Example

```rust
//! Create a bundle file and verify ref tips with [`Bundles`](https://grit-scm.com/docs/library/bundle/grit_lib::repo_handles::Bundles/index.md).
//!
//! Source for the library guide "Bundle" page (included in the docs site).

use anyhow::Result;
use grit_lib::bundle::BundleSpec;
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::objects::ObjectId;
use grit_lib::progress::{CancelToken, NullProgress};
use grit_lib::repo::Repository;

use std::path::{Path, PathBuf};

fn open_repo(root: &Path) -> Result<Repository> {
    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::from_process();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Ok(Repository::open(&git_dir, &opts)?)
}

fn main() -> Result<()> {
    let root = std::env::args()
        .nth(1)
        .map(PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .ok_or_else(|| anyhow::anyhow!("missing repository path"))?;
    let bundle_path = std::env::args()
        .nth(2)
        .map(PathBuf::from)
        .unwrap_or_else(|| root.join("guide.bundle"));

    let repo = open_repo(&root)?;
    let head = repo.references().head()?;
    let tip: ObjectId = head
        .oid()
        .cloned()
        .ok_or_else(|| anyhow::anyhow!("HEAD has no commit"))?;

    repo.bundles().write(
        &BundleSpec::default().with_include(vec![(tip, "refs/heads/main".into())]),
        &bundle_path,
        &mut NullProgress,
        &CancelToken::never(),
    )?;

    let report = repo.bundles().verify(&bundle_path)?;
    println!("bundle_ok={}", report.is_ok());

    let heads = repo.bundles().list_heads(&bundle_path, None)?.items;
    for head in heads {
        println!("bundle_head {} {}", head.name, head.oid.to_hex());
    }

    Ok(())
}
```

```bash
cargo run --bin guide_bundle . /tmp/demo.bundle
git bundle verify /tmp/demo.bundle
```

The test runs `git bundle verify` on the file grit wrote.
