以前我问过如何在 libgit2 中创建一个空提交。这个问题得到了充分的回答,但是当我最初问它时我还不够清楚。
使用 libgit2,如何创建一个空的初始提交?我上一个问题的答案依赖于父提交对象,我不知道如何为空存储库获取该对象。也许可以使用空树对象(可以使用 生成其散列git hash-object -t tree /dev/null)来完成某些事情?
在写我的问题时,我遇到了一个关于 libgit2 参考的例子,它正是我需要的。
Run Code Online (Sandbox Code Playgroud)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),然后使用它来获取空树,最后使用该树创建空初始提交。