简体   繁体   中英

how to checkout HEAD to specified reference or tag in libgit2?

I want to downgrade my program to previous version. Is it possible to do that in libgit2?

There is my code

string path = "C://Local//Path//to//my//repo";

string tag = "refs/tags/v0.0.4";

git_libgit2_init();

const char * REPO_PATH = path.c_str();

git_repository * repo = nullptr;

git_repository_open(&repo, REPO_PATH);

git_reference *ref;

git_reference_lookup(&ref, repo, "refs/heads/master");

git_reference *new_ref;

git_reference_symbolic_set_target(&new_ref, ref,tag.c_str(),"message");


git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;

// how to specify options to use ref or tag?

git_checkout_head(repo, &opts);

git_repository_free(repo);
git_libgit2_shutdown();

Think I got it

git_libgit2_init();

    const char * REPO_PATH = path.c_str();

    git_repository * repo = nullptr;
    git_repository_open(&repo, REPO_PATH);

    git_reference *ref;
    git_reference_lookup(&ref, repo, "refs/heads/master");      // "refs/remotes/origin/HEAD"

    git_reference *new_ref;
    git_reference_lookup(&new_ref, repo, tag.c_str());

    git_revwalk *walker;
    git_revwalk_new(&walker, repo);
    git_revwalk_push_ref(walker, tag.c_str());


    git_oid id;
    git_revwalk_next(&id, walker);

    git_reference_set_target(&new_ref, ref, &id, "message");

     git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;

    if (0!=git_repository_set_head_detached(repo,&id)) cerr<<"problem occured while detaching head"<< endl;

    if (0 != git_checkout_head(repo, &opts)) cerr << "problem checkout head" << endl;

    git_revwalk_free(walker);
    git_repository_free(repo);
    git_libgit2_shutdown();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM