Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add commit example #885

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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(())
}