How to hard reset to previous commit in libgit2?

Viewed 315

My program (which uses libgit2) makes a commit to local repo (no push, only commit), then does something and then, according to the result, tries to revert the last commit by resetting repo to HEAD~1 (one commit before HEAD). Simply hard reset.

The problem: the code below does reset HEAD to HEAD~1, but leaves all changes between these 2 commit as "staged", while I need to simply erase these changes. What am I doing wrong?

bool RevertLastCommit(std::string &errorMessage) 
{
    int error;
    git_object *head_commit_obj = nullptr;
    error = git_revparse_single(&head_commit_obj, repo, "HEAD~1");

    if (error < 0)
    {
        return false;
    }

    git_commit *head_commit = (git_commit *)head_commit_obj;

    git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
    opts.checkout_strategy = GIT_CHECKOUT_FORCE;
    
    int reset_result = git_reset(repo, const_cast<git_object *>(head_commit_obj), GIT_RESET_HARD, &opts);
    
    if (reset_result < 0) {
        printf("Reset failed!\n");
        return false;
    }

    printf("Done reverting\n");

    error = git_checkout_head(repo, &opts);
    if (error < 0)
    {
        return false;
    }

    printf("Hard checkout\n");
    return true;
}

0 Answers
Related