Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions examples/commit.rs
Original file line number Diff line number Diff line change
@@ -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", "[email protected]")?;
let commit_oid = repository.commit(
Some("HEAD"),
&signature,
&signature,
"Commit message",
&tree,
&parents[..],
)?;

let _commit = repository.find_commit(commit_oid)?;

Ok(())
}