1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
pub trait GitCommit {
    fn git_cmit(
        repo: &git2::Repository,
        message: &str,
    ) -> Result<(), git2::Error> {
        // 写入index
        let mut index = repo.index()?;
        let oid = index.write_tree()?;

        let tree = repo.find_tree(oid)?;

        // 获取当前HEAD的commit
        let head = repo.head().ok();
        let parent_commit = head.as_ref().and_then(|h| h.peel_to_commit().ok());

        let parents = parent_commit.iter().collect::<Vec<_>>();

        let conf = git2::Config::open_default()?;
        let name = conf.get_string("user.name")?;
        let email = conf.get_string("user.email")?;
        let signature = git2::Signature::now(&name, &email)?;

        repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &parents,
        )?;

        Ok(())
    }
}

// #[cfg(test)]
// mod tests {
//     use super::*;
//
//     #[test]
//     fn test_git_commit() {
//         git_commit(&git2::Repository::open(".").unwrap(), "Test").unwrap();
//     }
//
// }