使用 libgit2 在特定目录上调用 git diff

Calling git diff on a specific direcotry with libgit2

使用特定目录调用 git diff 在 cmd 上非常简单,但我需要从 C++ 程序中调用它。我对 libgit2 提供的所有不同的 diff 函数有点困惑,但在 问题的帮助下,我通过显示整个 repo 的结果来让它工作。对于我尝试使用 git_index_get_bypath 的特定路径,但它总是失败并显示中止消息。

git_index_get_bypath(index, "path/of/the/directory/inside/repo", GIT_INDEX_STAGE_NORMAL);

此外,每次我将回购路径更改为其中更具体的目录时,它都会因断言失败和中止消息而崩溃,这是有道理的。

我调用 git_diff_index_to_index(&diff, repo, NULL, index, &diffopts); 来获取与 diffopts.flags = GIT_DIFF_FORMAT_NAME_ONLY; 的差异


更新

git_repository *repo = NULL;
git_index *index = NULL;
git_diff *diff;
git_diff_options diffopts;

const char * REPO_PATH = "path/to/repo/"; 
//tried to be more specific with .../repo/.git but its the same thing
char *DIR_PATH = "path/to/repo/specific/dir"; 

git_repository_open(&repo, REPO_PATH);

diffopts = GIT_DIFF_OPTIONS_INIT;
diffopts.flags = GIT_DIFF_FORMAT_NAME_ONLY;

//diffopts.pathspec.count = 1;
//diffopts.pathspec.strings = &DIR_PATH;

git_repository_index(&index, repo);

git_diff_index_to_workdir(&diff, repo, index, &diffopts);

size_t num_deltas = git_diff_num_deltas(diff);

//do stuff with diff

取消注释

diffopts.pathspec.count = 1;
diffopts.pathspec.strings = &DIR_PATH;

git_diff_num_deltas returns 0.

如果您想将 diff 限制到特定文件夹,请将 diff 选项的 pathspec 设置为您感兴趣的路径。

例如:

char *path = "path/of/the/directory/inside/repo";
diffopts.pathspec.count = 1;
diffopts.pathspec.strings = &path;
git_diff_index_to_index(&diff, repo, NULL, index, &diffopts);

与库处理的大多数路径一样,它们通常与存储库的根目录相关(有一些注意事项,希望可以通过一些文档修复)。

在您的示例中,您将绝对路径传递给存储库(根据文档)和您感兴趣的路径规范。预期的是,差异时不会显示任何文件,因为路径在幕后被拼凑在一起。