Which is the equivalent of git checkout branch_name on LibGit2Sharp
I have 2 branches in git server which are master and development. I am cloning a repository to my machine using the following code.
var options =
new CloneOptions()
{
CredentialsProvider = this.credentialsHandler,
};
return
Repository.Clone(
gitHttpUrl,
localPath,
options);
The default split is master. I want to switch to developing a branch with the following code.
using (var repo = new Repository(localPath))
{
var branch = repo.Branches[branchName];
repo.Checkout(branch);
}
but the branch is null.
How can I switch a branch using LibGit2Sharp?
Update
Separation by default master
and below are the steps to reproduce the problem.
- Trailed
- Checkout
develop
branch - Pull, an exception is thrown here.
This is the code:
private void Checkout(string localPath, string branchName)
{
using (var repo = new Repository(localPath))
{
var branch = repo.Branches[branchName];
if (branch == null)
{
branch = repo.CreateBranch(branchName, "origin/" + branchName);
}
repo.Checkout(branch);
}
}
private MergeResult Pull(string path)
{
const string NAME = "test-user";
const string EMAIL = "test-email@gmail.com";
using (var repo = new Repository(path))
{
var merger =
new Signature(
NAME,
EMAIL,
DateTimeOffset.UtcNow);
var options =
new PullOptions
{
FetchOptions = new FetchOptions()
{
CredentialsProvider = this.credentialsHandler
}
};
return repo.Network.Pull(merger, options);
}
}
source to share
Similar to Git, when cloning LibGit2sharp will only create a local branch for the remote HEAD
All other branches will also be available and accessible as remote tracking branches, but a local branch will not automatically be created for them.
So, to achieve your goal, you can either checkout the remote tracking branch (for example origin/master
). Note that in this case HEAD will be automatically set in disconnected mode.
repo.Checkout["origin/my_branch"];
Or create a local branch from remote tracking and then checkout local.
var branch = repo.CreateBranch("my_branch", "origin/my_branch");
repo.Checkout(branch);
source to share