I want to create and delete a branch on git using libgit2sharp. I came up with this code but it throws an error at repo.Network.Push(localBranch, pushOptions);
using (var repo = new Repository(GIT_PATH))
{
var branch = repo.CreateBranch(branchName);
var localBranch = repo.Branches[branchName];
//repo.Index.Stage(GIT_PATH);
repo.Checkout(localBranch);
repo.Commit("Commiting at " + DateTime.Now);
var pushOptions = new PushOptions() { Credentials = credentials };
repo.Network.Push(localBranch, pushOptions); // error
branch = repo.Branches["origin/master"];
repo.Network.Push(branch, pushOptions);
}
The error message is The branch 'buggy-3' ("refs/heads/buggy-3") that you are trying to push does not track an upstream branch.
I tried searching this error on the internet but no solution that I found could fix the problem. Is it possible to do this using libgit2sharp?
The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.
In order to push your branch to another remote branch, use the “git push” command and specify the remote name, the name of your local branch as the name of the remote branch.
From Sourcetree, click the Branch button. From the New Branch field, enter a name for your branch. Click Create Branch. You're now on your new branch.
You have to associate your local branch with a remote against which you'd like to push.
For instance, given an already existing "origin"
remote:
Remote remote = repo.Network.Remotes["origin"];
// The local branch "buggy-3" will track a branch also named "buggy-3"
// in the repository pointed at by "origin"
repo.Branches.Update(localBranch,
b => b.Remote = remote.Name,
b => b.UpstreamBranch = localBranch.CanonicalName);
// Thus Push will know where to push this branch (eg. the remote)
// and which branch it should target in the target repository
repo.Network.Push(localBranch, pushOptions);
// Do some stuff
....
// One can call Push() again without having to configure the branch
// as everything has already been persisted in the repository config file
repo.Network.Push(localBranch, pushOptions);
Note:: Push()
exposes other overloads that allow you to dynamically provide such information without storing it in the config.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With