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

时间:2019-02-19 22:54:31

标签: c++ git git-diff libgit2

在cmd上调用具有特定目录的git diff非常简单,但是我需要从c ++程序中调用它。我对libgit2提供的所有不同的diff函数感到有些困惑,但是在this问题的帮助下,我通过显示整个存储库的结果来使其工作。对于特定的路径,我尝试使用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返回0。

2 个答案:

答案 0 :(得分:2)

与库处理的大多数路径一样,它们通常相对于存储库的根目录(有一些警告,希望可以通过一些文档进行修复)。

在您的示例中,您正在将绝对路径传递到存储库(根据文档)和您感兴趣的路径规范。可以预期的是,差异时不会显示任何文件,因为路径是在后台隐藏在一起的。

答案 1 :(得分: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);