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.

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::objects::{parse_commit, ObjectKind};
use grit_lib::repo::Repository;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let repo = Repository::discover(None)?;
    let head = grit_lib::refs::resolve_ref(&repo.git_dir, "HEAD")?;
    let object = repo.odb.read(&head)?;
    if object.kind != ObjectKind::Commit {
        return Err("HEAD is not a commit".into());
    }
    let commit = parse_commit(&object.data)?;
    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

Next steps