12

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?

Steven V
  • 16,357
  • 3
  • 63
  • 76
Anonymous
  • 9,366
  • 22
  • 83
  • 133

1 Answers1

25

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.

nulltoken
  • 64,429
  • 20
  • 138
  • 130
  • See also this **[SO answer](http://stackoverflow.com/a/22617675/335418)** which should provide you with futher details regarding the branch configuration – nulltoken Apr 10 '14 at 08:50
  • Where is the difference between `localRepo` and `repo`? – BendEg Jul 08 '15 at 11:52