Michael Chourdakis
Michael Chourdakis

Reputation: 11158

LibGit2 Commit example

I am trying to use LibGit2, and I 'm stuck in commit. I 've tried this one which works only for the "initial" commit. For next commits, it fails with -15 "current tip is not the first parent".

Two questions:

  1. How do I know If i need an initial commit ?
  2. How do I perform a non-initial commit?

Thx.

Upvotes: 4

Views: 4325

Answers (1)

Schwern
Schwern

Reputation: 164659

How do I know If i need an initial commit ?

You can check git_repository_head_unborn() to see if HEAD points at a reference or not.

How do I perform a non-initial commit?

You need to supply the index to be committed. This is easiest done with git_repository_index(). However, the index must be supplied as a tree. The confusingly named git_index_write_tree() will write the index to a tree for you.

To get the parent(s), use git_oid_fromstr() to get an object id from a hash or git_reference_name_to_id() to get it from a reference name such as "HEAD". Then use git_commit_lookup() to get the commit object(s) from the oids.

Then pass them into git_commit_create() or git_commit_create_v(). Using git_commit_create_v() avoids having to make a list of git_commit pointers, just pass the commits in as arguments like printf().

There is a good example in ex/general.c which does a better job explaining all the steps than I will. I also like to use Git::Raw, the Perl wrapper around libgit2, as an example. Look at the .xs files (which are basically C).

Here is an untested example of committing the index to HEAD. I'm assuming you already have the author, committer and repo.

git_oid tree_id, parent_id, commit_id;
git_tree *tree;
git_commit *parent;
git_index *index;

/* Get the index and write it to a tree */
git_repository_index(&index, repo);
git_index_write_tree(tree, index);

/* Get HEAD as a commit object to use as the parent of the commit */
git_reference_name_to_id(parent_id, repo, "HEAD");
git_commit_lookup(&parent, repo, parent_id);

/* Do the commit */
git_commit_create_v(
    commit_id,
    repo,
    "HEAD",     /* The commit will update the position of HEAD */
    author,
    committer,
    NULL,       /* UTF-8 encoding */
    message,
    tree,       /* The tree from the index */
    1,          /* Only one parent */
    parent      /* No need to make a list with create_v */
);

Upvotes: 15

Related Questions