简体   繁体   中英

How to get the last commit from HEAD in a git repository using libgit2?

Since there is no copy-paste example for getting last commit with libgit2 I thought I should add one. The examples in libgit2 make extensive use of git_oid_fromstr() ...

Don't forget that libgit2 is in full development at this time (March 2013) so have a look at official documentation and source code, as new features are added daily:

git_commit * getLastCommit ( git_repository * repo )
{
  int rc;
  git_commit * commit = NULL; /* the result */
  git_oid oid_parent_commit;  /* the SHA1 for last commit */

  /* resolve HEAD into a SHA1 */
  rc = git_reference_name_to_id( &oid_parent_commit, repo, "HEAD" );
  if ( rc == 0 )
  {
    /* get the actual commit structure */
    rc = git_commit_lookup( &commit, repo, &oid_parent_commit );
    if ( rc == 0 )
    {
      return commit;
    }
  }
  return NULL;
}

You will need to call git_commit_free() once you are done with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM