Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git checkout with libgit2

This question is an evolution or resolution my previous question: Clone a git repo (in depth) I think creating a new question is the best thing to do in this situation, but I may be wrong.

This one is simple: how would I do something equivalent of git checkout master with libgit2

It seems like it was not possible a year ago: https://github.com/libgit2/libgit2/issues/247 According to this a clone was possible at least 5 months ago. But I have never seen any code, documentation or examples about how to do it. (Edit) I mean I haven't seen anything about a complete clone with git checkout included, nor any code/docs about the checkout.

like image 747
Johannes Lund Avatar asked Feb 20 '23 07:02

Johannes Lund


2 Answers

According to this a clone was possible at least 5 months ago. But I have never seen any code, documentation or examples about how to do it.

The clone operation is basically made of four steps:

  • Initialize a new repository
  • Add a remote with a fetch refspec
  • Fetch the packfile from the remote and update your local references
  • Update the content of the workdir from the commit tree of the HEAD

Current version of libgit2 (v0.17.0) allows one to perform the three first steps.

The source code contains some examples. There's a "fetch.c" one as well.

how would I do something equivalent of git checkout master with libgit2

Checkout is not implemented yet. However, the following should help you go forward.

  • git_reference_name_to_oid() to retrieve the oid of the master branch
  • git_commit_lookup() to retreive a commit from an oid
  • git_commit_tree() to retrieve the tree of a commit
  • git_iterator_for_tree() to recursively browse all the leafs of the tree (and its subtrees)

Update

The clone feature has just been merged into the libgit2 repository.

  • clone.h header
  • sample code usage in examples/network/clone.c

As part of the pull request, the author took care of providing the users with a checkout implementation as well.

  • checkout.h header
  • checkout related unit tests
like image 145
nulltoken Avatar answered Mar 03 '23 11:03

nulltoken


You can create a HEAD symbolic, then checkout to head, like

git_reference_create_symbolic(&head, repo, GIT_HEAD_FILE, branchname, 1);
git_checkout_head(repo, opts, stat);
like image 32
Zhengming Ying Avatar answered Mar 03 '23 11:03

Zhengming Ying