workon/empty_commit.rs
1use git2::{Oid, Repository};
2
3use crate::{error::Result, WorktreeError};
4
5/// Create an empty initial commit on HEAD with no parents.
6///
7/// Used when initialising a new bare repository to ensure HEAD points to a
8/// valid commit. Returns [`WorktreeError::NonEmptyIndex`] if the index is not
9/// empty when called.
10pub fn empty_commit(repo: &Repository) -> Result<Oid> {
11 let sig = repo.signature()?;
12 let tree = repo.find_tree({
13 let mut index = repo.index()?;
14 index.write_tree()?
15 })?;
16
17 if !tree.is_empty() {
18 return Err(WorktreeError::NonEmptyIndex.into());
19 }
20
21 Ok(repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])?)
22}