1use crate::GitResult;
2use git2::{Commit, Error, Repository, Sort};
3
4pub fn find_closest_git_repo() -> GitResult<Repository> {
6 let mut current_dir = match std::env::current_dir() {
7 Ok(dir) => dir,
8 Err(_) => return Err(Error::from_str("Can not get current directory")),
9 };
10 loop {
11 if current_dir.join(".git").exists() {
12 return Ok(Repository::open(current_dir)?);
13 }
14 if !current_dir.pop() {
15 break;
16 }
17 }
18 Err(Error::from_str("No git repository found"))
19}
20
21pub fn find_initial_commit(repo: &Repository) -> GitResult<Commit> {
22 let mut revwalk = repo.revwalk()?;
23 revwalk.push_head()?;
24 revwalk.set_sorting(Sort::TIME)?;
25 for oid in revwalk {
26 let oid = oid?;
27 let commit = repo.find_commit(oid)?;
28 if commit.parent_count() == 0 {
29 return Ok(commit);
30 }
31 }
32 Err(Error::from_str("No initial commit found"))
33}