首页 > 解决方案 > 如何通过在 libgit2 中创建内存索引来提交文件?

问题描述

创建您自己的内存索引并使用它来代替存储库的索引。但我无法初始化它。错误消息是could not initialize index entry, Index is not backed up by an existing repository,请执行以下操作:

...
git_repository_open(&repo, ...); // same as before
git_index_new(&index); // create in-memory index
git_revparse_single(headTree, repo, "HEAD^{tree}");  // get head Tree
git_index_read_tree(index, headTree); // initialize to the current HEAD
git_index_add_by_path(index, "1.txt"); //update the nominated file(s).but it not work 
git_index_write_tree_to(&oid, index, repo); // write the tree into the repo
git_tree_lookup(&tree, repo, &oid); // same as before
...

标签: libgit2

解决方案


您的内存索引未绑定到存储库。因此,您不能做隐含接触工作目录的事情 - 因为这是一个与存储库对象相关的概念,并且没有一个用于您的索引。

因此git_index_add_by_path,在内存索引上操作时会失败。它找不到那条路径,它不知道在哪里寻找它。

git_index_add_by_path通过读取磁盘上的文件来创建一个git_index_entry. 这是一个便利功能。

相反,您可以使用git_index_add索引条目数据。


推荐阅读