Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libgit2 git_checkout_head with GIT_CHECKOUT_SAFE do nothing with working dir

Tags:

c

libgit2

I'm trying to do branch switching using libgit2. Repo already cloned and references to existing remote branches created.

If I put GIT_CHECKOUT_FORCE to checkout_strategy, it works as expected - create missing, modify existing, delete removed.

If GIT_CHECKOUT_RECREATE_MISSING - create missing only.

If GIT_CHECKOUT_SAFE - do nothing. Am I missing something?

git_reference_lookup(&branch_ref, repo, ref_name);
git_repository_set_head(repo, git_reference_name(branch_ref));
git_reference_symbolic_create(&head, repo, "HEAD", git_reference_name(branch_ref), 1, NULL);
git_checkout_head(repo, &opts);

I got branches

  • master (current): f1.txt f2.txt
  • new: f1.txt (content differs from master's one)

After GIT_CHECKOUT_SAFE to new:

  • f1.txt (content from master)
  • f2.txt (staged to commit)
like image 737
Vadim Avatar asked Jul 04 '19 09:07

Vadim


1 Answers

I believe the problem is the state the the repo is in at the time you try to checkout the HEAD. Before your code runs, you have:

on disk  - f1: master's content, f2: master's content
in index - f1: master's content, f2: master's content
in HEAD  - f1: master's content, f2: master's content

After you update your HEAD to point to your new branch, you now have:

on disk  - f1: master's content, f2: master's content
in index - f1: master's content, f2: master's content
in HEAD  - f1: new's content,    f2: absent

To git, this is indistinguishable from you being on the new branch, making changes to f1 and git adding those changes to the index. (In other words, git will describe these as "to be committed".) So, when you ask it to checkout the HEAD content in safe mode, it refuses to throw away your changes.

Similarly, for f2, it appears to be a newly-added file and so safe mode doesn't remove it.

I resolved these issues by using git_checkout_tree first to make the content match the new branch (so libgit2 can see the content matches HEAD and therefore is safe to blow away), and then updating the HEAD pointer afterwards.

like image 121
Jesse Rusak Avatar answered Oct 02 '22 02:10

Jesse Rusak