如何从给定的文件提交?

How to commit from the given files?

我需要使用 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"

您想提出一个树对象以传递给 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
...

方法一:

要么修改存储库的索引以反映您要提交的内容:调用 git_index_add 将 2.txt 的数据放回索引中,然后在为提交创建树后再次删除它.

方法二:

将存储库的索引复制为临时的内存中索引并改变该索引,将 1.txt 添加回去。然后从该索引而不是存储库的索引创建树。 git_index_add_by_path 在内存索引上操作时将失败。它找不到那条路径,它不知道去哪里寻找它。 Git_index_add_by_path 通过读取磁盘上的文件来创建 git_index_entry。这是一个方便的功能。 相反,您可以将 git_index_add 与索引条目数据一起使用。