Question

How can I create a local branch that tracks a remote branch with libgit2sharp? The git equivalent would be:

git branch --track development origin/development
Was it helpful?

Solution

The following code should just do that, assuming the local development branch doesn't exist yet.

const string testBranchName = "development";
const string trackedBranchName = "origin/development";

using (var repo = new Repository(path))
{
    // Retrieve remote tracking branch
    Branch trackedBranch = repo.Branches[trackedBranchName];
    Debug.Assert(trackedBranch.IsRemote == true);

    // Create local branch pointing at the same Commit
    Branch branch = repo.CreateBranch(testBranchName, trackedBranch.Tip);

    repo.Branches.Update(branch,
        b => b.TrackedBranch = trackedBranch.CanonicalName);
}

Note: The BranchFixture.cs suite contains a CanSetTrackedBranch test which should provide you with further usage details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top