git_utils/
commits.rs

1use crate::{find_initial_commit, GitResult};
2use git2::{Branch, BranchType, Error, ObjectType, Oid, Repository, Signature, Sort};
3
4// Function to count commits between a commit and HEAD
5pub fn count_commits_from(id: Oid, repo: &Repository) -> GitResult<usize> {
6    let mut count: usize = 0;
7    let mut revwalk = repo.revwalk()?;
8    revwalk.push_head()?;
9    revwalk.set_sorting(Sort::TIME)?;
10
11    for commit_id in revwalk {
12        let commit_id = commit_id?;
13        if commit_id == id {
14            break;
15        }
16        count += 1;
17    }
18    // count = count.saturating_sub(1);
19    Ok(count)
20}
21
22/// Reword the root commit of the old branch and create a new branch
23///
24/// # Arguments
25///
26/// * `repo`:  The git repository
27/// * `message`:  The initial commit message
28/// * `old`:  The old branch name
29/// * `new`: The new branch name
30pub fn reword_root_commit<'a>(repo: &'a Repository, old: &str, new: &str, message: &str) -> GitResult<Branch<'a>> {
31    let old_branch = repo.find_branch(old, BranchType::Local)?;
32    let old_commit = old_branch.get().peel_to_commit()?;
33    let old_tree = old_commit.tree()?;
34    let init_tree = repo.treebuilder(Some(&old_tree))?.write()?;
35    let init_oid = repo.commit(None, &repo.signature()?, &repo.signature()?, message, &repo.find_tree(init_tree)?, &[])?;
36    let new_branch = repo.branch(new, &repo.find_commit(init_oid)?, false)?;
37    Ok(new_branch)
38}