use git2::{Repository, Signature, IndexAddOption};
use std::path::Path;
use crate::error::Result;
pub struct GitManager {
repo: Repository,
}
impl GitManager {
pub fn new(path: &Path) -> Result<Self> {
let repo = match Repository::open(path) {
Ok(repo) => repo,
Err(_) => Repository::init(path)?,
};
Ok(Self { repo })
}
pub fn commit(&self, message: &str) -> Result<()> {
let mut index = self.repo.index()?;
index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None)?;
index.write()?;
let tree_id = index.write_tree()?;
let tree = self.repo.find_tree(tree_id)?;
let signature = Signature::now("LoreFS", "lorefs@gemini.cli")?;
let parent_commit = match self.repo.head() {
Ok(head) => Some(head.peel_to_commit()?),
Err(_) => None,
};
let parents = match &parent_commit {
Some(c) => vec![c],
None => vec![],
};
self.repo.commit(
Some("HEAD"),
&signature,
&signature,
message,
&tree,
&parents,
)?;
Ok(())
}
}