From 76639568168840af4c3ba3b182d4a7139e14cfb5 Mon Sep 17 00:00:00 2001 From: TrAyZeN <1810leo@gmail.com> Date: Wed, 28 Sep 2022 10:28:27 +0200 Subject: [PATCH] Add commit example --- examples/commit.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 examples/commit.rs diff --git a/examples/commit.rs b/examples/commit.rs new file mode 100644 index 0000000000..4594cd2707 --- /dev/null +++ b/examples/commit.rs @@ -0,0 +1,36 @@ +use git2::{Error, ErrorCode, Repository, Signature}; + +fn main() -> Result<(), Error> { + let repository = Repository::open(".")?; + + // We will commit the content of the index + let mut index = repository.index()?; + let tree_oid = index.write_tree()?; + let tree = repository.find_tree(tree_oid)?; + + let parent_commit = match repository.revparse_single("HEAD") { + Ok(obj) => Some(obj.into_commit().unwrap()), + // First commit so no parent commit + Err(e) if e.code() == ErrorCode::NotFound => None, + Err(e) => return Err(e), + }; + + let mut parents = Vec::new(); + if parent_commit.is_some() { + parents.push(parent_commit.as_ref().unwrap()); + } + + let signature = Signature::now("username", "username@example.com")?; + let commit_oid = repository.commit( + Some("HEAD"), + &signature, + &signature, + "Commit message", + &tree, + &parents[..], + )?; + + let _commit = repository.find_commit(commit_oid)?; + + Ok(()) +}