首页 > 解决方案 > 如何从给定文件提交?

问题描述

我需要使用 libgit2 来实现“git commit -F ...”命令。

下面的代码将提交 1.txt 和 2.txt:

git_libgit2_init();

git_repository* pRepository;
git_index* pIndex;
git_oid oidTree, oidCommitted;
git_tree* pTree;
git_signature* pSignature;

git_repository_init(&pRepository, "C:\\Temp", false);
git_repository_index(&pIndex, pRepository);
git_index_add_bypath(pIndex, "1.txt");
git_index_add_bypath(pIndex, "2.txt");
git_index_write(pIndex);
git_index_write_tree(&oidTree, pIndex);
git_tree_lookup(&pTree, pRepository, &oidTree);
git_signature_now(&pSignature, "My name", "My email");
git_commit_create(&oidCommitted, pRepository, "refs/heads/master",
    pSignature, pSignature, NULL, "Initial commit with 1.txt", pTree, 0, NULL);
git_signature_free(pSignature);
git_tree_free(pTree);
git_index_free(pIndex);
git_repository_free(pRepository);

git_libgit2_shutdown();

如何更改我的代码以实现:

git add 1.txt 2.txt
git commit 1.txt -m "Initial commit with 1.txt"

标签: libgit2

解决方案


您想在git_commit_create不修改存储库索引的情况下提供一个要传递的树对象。有几种方法可以做到这一点。最简单的方法是创建自己的内存索引并使用它来代替存储库的索引。本质上,做这样的事情:

...
git_repository_init(&repo, ...); // same as before
git_index_new(&index); // create in-memory index
git_index_read_tree(index, headTree); // initialize to the current HEAD
git_index_add_by_path(index, "1.txt"); // update the nominated file(s)
git_index_write_tree_to(&oid, index, repo); // write the tree into the repo
git_tree_lookup(&tree, repo, &oid); // same as before
...

推荐阅读