如何在 libgit2 中打印差异文件?

how to print diff files in libgit2?

我试过了

string path = "path/to/my/repo";
git_libgit2_init();
const char * REPO_PATH = path.c_str();
git_repository * repo = nullptr;
git_repository_open(&repo, REPO_PATH);

git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT;
git_diff *diff;
diffopts.flags = GIT_CHECKOUT_NOTIFY_CONFLICT;
git_diff_index_to_workdir(&diff, repo, NULL, &diffopts);
git_diff_format_t format = GIT_DIFF_FORMAT_NAME_ONLY;

if (0!=git_diff_print(diff, format, NULL,NULL)) cerr << "git_diff_print() failed" << endl;

git_diff_free(diff);
git_repository_free(repo);
git_libgit2_shutdown();

但我不知道将什么作为第 3 个和第 4 个参数发送给函数 git_diff_print(),一些想法?

在libgit2中API,有这个函数的声明

git_diff_print(git_diff *diff, git_diff_format_t format, git_diff_line_cb print_cb, void *payload);

但我不知道最后两个参数是什么以及如何将它们发送到此函数

当我尝试这个例子时:

https://libgit2.github.com/libgit2/ex/HEAD/diff.html#git_diff_print-9

,它不适合我

终于,我通过其他方式得到了信息,这就是我的解决方案:

git_libgit2_init();
const char * REPO_PATH = path.c_str();
git_repository * repo = nullptr;
git_repository_open(&repo, REPO_PATH);

git_diff_options diffopts = GIT_DIFF_OPTIONS_INIT;
git_diff *diff;
diffopts.flags = GIT_CHECKOUT_NOTIFY_CONFLICT;
git_diff_index_to_workdir(&diff, repo, NULL, &diffopts);

size_t num_deltas = git_diff_num_deltas(diff);
if (num_deltas != 0){
    const git_diff_delta *delta = git_diff_get_delta(diff, 0);
    int i = 0;
    cerr << "Your local changes to the following files would be overwritten by checkout : " << endl;

    while (i<num_deltas) {
        delta = git_diff_get_delta(diff, i);
        git_diff_file file = delta->new_file;
        cerr << "\t" << file.path << endl;
        i++;

    }
    cerr << "Please commit your changes before you switch branches. " << endl;

}
else cout << "All files OK, can checkout now" << endl;

git_diff_free(diff);
git_repository_free(repo);
git_libgit2_shutdown();