libgit2没有返回有效的blob

问题描述 投票:0回答:1

我正在尝试使用libgit2获取存储库的blob:

#include <git2.h>
#include <stdio.h>

int main() {

    git_libgit2_init();

    git_repository *repo = NULL;
    int error = git_repository_open(&repo, "/home/martin/Dokumente/TestRepository");

    if (error < 0) {
  const git_error *e = git_error_last();
  printf("Error %d/%d: %s\n", error, e->klass, e->message);
  exit(error);
}

git_diff *diff = NULL;
git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
opts.flags |= GIT_DIFF_IGNORE_WHITESPACE;
opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED;

error = git_diff_index_to_workdir(&diff, repo, NULL, &opts);
if (error < 0) {
  const git_error *e = git_error_last();
  printf("Error %d/%d: %s\n", error, e->klass, e->message);
  exit(error);
}

git_patch* patch = nullptr;
git_patch_from_diff(&patch, diff, 0);

bool oldFile = false;
const git_diff_delta *dd = git_patch_get_delta(patch);
const git_oid &id = (!oldFile) ? dd->new_file.id : dd->old_file.id;

git_object *obj = nullptr;
git_object_lookup(&obj, repo, &id, GIT_OBJECT_ANY);
git_blob* blob = reinterpret_cast<git_blob *>(obj);

const char* pointer = (const char*)git_blob_rawcontent(blob);

// cleanup
git_object_free(obj);
git_patch_free(patch);
git_diff_free(diff);
git_repository_free(repo);

return 0;
}

存储库

  • 创建新的存储库

  • 提交类似文件:

    1234

  • 再次删除4,但不要提交

  • 让程序运行

期望:该程序运行正常。

已观察:执行后obj仍然是nullptrgit_object_lookup()

将变量oldFile设置为true时,程序运行良好,并且指针“ pointer”包含原始blob。

有人知道为什么我没有从git_object_lookup()返回有效的对象吗?

c git libgit2 gitahead
1个回答
0
投票

当您在索引和工作目录之间进行区分时,增量的new端代表工作目录中的文件。其id是磁盘上文件的哈希。除非您通过其他方式将该Blob明确插入到存储库的对象存储中,否则没有理由将其存在。


0
投票

问题是您正在尝试获取ID为dd->new_file.id的对象。该文件位于工作目录中,因为尚未添加或提交。这意味着它尚未在存储库中。运行git_object_lookup()时,找不到对象,因为它尚未添加到树中。 OID不对应任何匹配项,因此它返回null。

© www.soinside.com 2019 - 2024. All rights reserved.