Skip to main content

index_add/
index_add.rs

1//! Build an in-memory [`Index`], stage a path, and write `.git/index` via [`Repository::write_index`].
2//!
3//! Run: `cargo run -p grit-lib --example index_add`
4
5use grit_lib::index::{Index, IndexEntry, MODE_REGULAR};
6use grit_lib::objects::ObjectKind;
7use grit_lib::repo::init_repository;
8
9fn main() -> grit_lib::error::Result<()> {
10    let root = tempfile::tempdir()?;
11    let repo = init_repository(root.path(), false, "main", None, "files")?;
12
13    let blob_oid = repo.odb.write(ObjectKind::Blob, b"staged content\n")?;
14
15    let path = b"notes.txt".to_vec();
16    let entry = IndexEntry {
17        ctime_sec: 0,
18        ctime_nsec: 0,
19        mtime_sec: 0,
20        mtime_nsec: 0,
21        dev: 0,
22        ino: 0,
23        mode: MODE_REGULAR,
24        uid: 0,
25        gid: 0,
26        size: 0,
27        oid: blob_oid,
28        flags: (path.len().min(0xfff)) as u16,
29        flags_extended: None,
30        path,
31        base_index_pos: 0,
32    };
33
34    let mut index = Index::new();
35    index.add_or_replace(entry);
36    repo.write_index(&mut index)?;
37
38    let round_trip = repo.load_index()?;
39    println!("index entries: {}", round_trip.entries.len());
40    let first = &round_trip.entries[0];
41    println!(
42        "first path: {}, oid: {}",
43        String::from_utf8_lossy(&first.path),
44        first.oid
45    );
46
47    Ok(())
48}