简体   繁体   中英

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

Previously I had asked how one could create an empty commit in libgit2 . That question was fully answered, however I wasn't clear enough when I initially asked it.

Using libgit2, how can one create an empty initial commit? The answer to my previous question relies on having the parent commit object, which I don't know how to obtain for an empty repository. Perhaps something could be done using the empty tree object (whose hash can be generated with git hash-object -t tree /dev/null )?

While writing my question, I came across an example on the libgit2 reference , which had exactly what I needed.

 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); }

This function creates an empty initial commit. It reads the index from the empty repository, then uses that to obtains the ID of the empty tree ( 4b825dc642cb6eb9a060e54bf8d69288fbee4904 ), then uses that to obtain the empty tree, and finally creates the empty initial commit using that tree.

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