grit
CLILibrary
HEAD → docs/library-quickstart
Getting started / Library quick startMarkdown

Library quick start

Add grit-lib to a Rust project, open a repository, and read the current commit from HEAD.

This page walks through a minimal program that discovers a Git repository in the current directory (or a parent), resolves HEAD, and prints the commit id and subject line. The source below is the real example binary in the Grit repository; it is included automatically so the docs cannot drift from compiled code.

01

Add the dependency

Use the latest version on crates.io if the number above is stale.

grit-lib requires Rust 1.95 or newer (rust-version in the crate manifest). That applies when you add the dependency from crates.io or a path outside the Grit workspace. Building inside the Grit repository uses the contributor toolchain pin in rust-toolchain.toml (currently 1.99.0), which does not propagate to downstream crates.

In your crate
$ cargo add grit-lib
Or add to Cargo.toml
[dependencies]
grit-lib = "0.5.0"
02

Example program

Save as src/main.rs (or copy from grit-examples in the Grit repo):

//! Minimal grit-lib program: discover a repository and print HEAD's commit id.
//!
//! Source for the library quick start in the docs; kept in sync via an include directive.

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::refs::store::RefName;
use grit_lib::repo::Repository;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let repo = Repository::discover(None, &RepositoryOptions::from_process())?;
    let head_name = RefName::try_from("HEAD")?;
    let head = repo.references().resolve(&head_name)?;
    let commit = repo.objects().read_commit(&head)?;
    println!("{head}");
    let subject = commit.message.lines().next().unwrap_or("");
    if !subject.is_empty() {
        println!("{subject}");
    }
    Ok(())
}
03

Run it

From the root of any Git repository with at least one commit:

The first line is the full object id of HEAD; the second is the first line of the commit message.

$ cargo run
Example output (your commit id will differ)
217c6f9a1b2c3d4e5f6789012345678901234567
Start the project
04

The environment

The program opens the repository with RepositoryOptions::from_process, which snapshots the process environment (HOME, GIT_*, Windows ProgramFiles) so system and global config apply exactly as they do for git and grit: core.autocrlf, user.name and user.email, safe.directory, core.excludesFile and credential helpers. The library itself never reads the process environment. RepositoryOptions::empty is the hermetic alternative for tests: no home directory and no global config. See Embedding grit-lib.

05

Next steps