Skip to main content

commit_tree/
commit_tree.rs

1//! Stage paths in the index, build a tree with [`write_tree::write_tree_from_index`], create a
2//! commit with [`objects::serialize_commit`], and point `refs/heads/main` at it with [`refs::write_ref`].
3//!
4//! Run: `cargo run -p grit-lib --example commit_tree`
5
6use grit_lib::index::{Index, IndexEntry, MODE_REGULAR};
7use grit_lib::objects::{serialize_commit, CommitData, ObjectKind};
8use grit_lib::refs;
9use grit_lib::repo::init_repository;
10use grit_lib::write_tree::write_tree_from_index;
11
12fn main() -> grit_lib::error::Result<()> {
13    let root = tempfile::tempdir()?;
14    let repo = init_repository(root.path(), false, "main", None, "files")?;
15
16    let blob_oid = repo
17        .odb
18        .write(ObjectKind::Blob, b"hello from grit-lib examples\n")?;
19    let path = b"README".to_vec();
20    let entry = IndexEntry {
21        ctime_sec: 0,
22        ctime_nsec: 0,
23        mtime_sec: 0,
24        mtime_nsec: 0,
25        dev: 0,
26        ino: 0,
27        mode: MODE_REGULAR,
28        uid: 0,
29        gid: 0,
30        size: 0,
31        oid: blob_oid,
32        flags: (path.len().min(0xfff)) as u16,
33        flags_extended: None,
34        path,
35        base_index_pos: 0,
36    };
37
38    let mut index = Index::new();
39    index.add_or_replace(entry);
40    repo.write_index(&mut index)?;
41
42    let index = repo.load_index()?;
43    let tree_oid = write_tree_from_index(&repo.odb, &index, "")?;
44    println!("tree: {tree_oid}");
45
46    let commit = CommitData {
47        tree: tree_oid,
48        parents: Vec::new(),
49        author: "Example <example@example.com> 1700000000 +0000".to_owned(),
50        committer: "Example <example@example.com> 1700000000 +0000".to_owned(),
51        author_raw: Vec::new(),
52        committer_raw: Vec::new(),
53        encoding: None,
54        message: "initial example commit\n".to_owned(),
55        raw_message: None,
56    };
57    let raw = serialize_commit(&commit);
58    let commit_oid = repo.odb.write(ObjectKind::Commit, &raw)?;
59    println!("commit: {commit_oid}");
60
61    refs::write_ref(&repo.git_dir, "refs/heads/main", &commit_oid)?;
62    println!("updated refs/heads/main -> {commit_oid}");
63
64    Ok(())
65}