如何在libgit2中打印diff文件?

时间:2017-05-03 05:57:54

标签: c++ 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);

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

当我尝试这个例子时:

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

,它不适合我

1 个答案:

答案 0 :(得分:1)

最后,我得到了另一种信息,有我的解决方案:

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();