Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use libgit2sharp to create a new branch from local to remote?

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?

like image 562
Anonymous Avatar asked Apr 10 '14 07:04

Anonymous


People also ask

How do I create a new branch and push to it in terminal?

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.

How push local branch to remote with same name?

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.

How do I create a remote branch in Sourcetree?

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.


1 Answers

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.

like image 154
nulltoken Avatar answered Oct 03 '22 23:10

nulltoken