Search code examples
c++libgit2

how to set checkout options in libgit2 to behave like "git checkout"


I am working in some branch, but now I want to checkout to another specified branch. When I set checkout options like this

git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
opts.checkout_strategy = GIT_CHECKOUT_FORCE;

checkout is performed and all my files in repository are changed to files in checkouted branch...

If I have performed commit in the first branch, everything is clear, but if I don't, I lost all of my uncommited changes.

Is there a way that this will behave like "git checkout" in terminal? I mean that when I perform checkout, program realizes if there are some uncommited changes,

->if there are not - checkout is happening

->if there are some uncommited changes, it prints some information like git terminal

for example message from terminal :

Your local changes to the following files would be overwritten by checkout: output.csv


I think I have to set different checkout strategy, but I have no idea about which would be the best

I tried also

opts.checkout_strategy = GIT_CHECKOUT_NOTIFY_DIRTY;

but it behave the same as force


Solution

  • Finally, I got the information another way, there is my solution :

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