使用libgit2,如何创建一个空的初始提交?

时间:2018-09-12 18:05:39

标签: c git libgit2

以前,我曾问过how one could create an empty commit in libgit2。这个问题已得到完全回答,但是当我最初问它时,我还不够清楚。

使用libgit2,如何创建一个空的初始提交? “如何使用libgit2创建空提交”的答案取决于拥有父提交对象,而我不知道如何获取空存储库。也许可以使用空树对象(可以通过git hash-object -t tree /dev/null生成其哈希值)来完成某些工作?

1 个答案:

答案 0 :(得分:4)

在写问题时,我碰到了example on the libgit2 reference,正是我所需要的。

static void create_initial_commit(git_repository *repo)
{
  git_signature *sig;
  git_index *index;
  git_oid tree_id, commit_id;
  git_tree *tree;

if (git_signature_default(&sig, repo) < 0)
    fatal("Unable to create a commit signature.",
          "Perhaps 'user.name' and 'user.email' are not set");

 if (git_repository_index(&index, repo) < 0)
    fatal("Could not open repository index", NULL);

 if (git_index_write_tree(&tree_id, index) < 0)
    fatal("Unable to write initial tree from index", NULL);

 git_index_free(index);

 if (git_tree_lookup(&tree, repo, &tree_id) < 0)
    fatal("Could not look up initial tree", NULL);

 if (git_commit_create_v(
      &commit_id, repo, "HEAD", sig, sig,
      NULL, "Initial commit", tree, 0) < 0)
    fatal("Could not create the initial commit", NULL);

  git_tree_free(tree);
  git_signature_free(sig);
}

此函数创建一个空的初始提交。它从空存储库中读取索引,然后使用它来获取空树的ID(4b825dc642cb6eb9a060e54bf8d69288fbee4904),然后使用它来获取空树,最后使用该树来创建空初始提交。