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

Using libgit2, how can an empty initial commit be created?

之前我问过。这个问题已经完全回答了,但是我最初问的时候还不够清楚

使用 libgit2,如何创建一个空的 initial 提交? 的答案依赖于拥有父提交对象,我不知道如何为空存储库获取该对象。也许可以使用空树对象(其哈希可以用 git hash-object -t tree /dev/null 生成)来完成一些事情?

在写我的问题时,我遇到了一个 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),然后使用它来获取空树,最后使用该树创建空的初始提交。