如何使用libgit2sharp创建从本地到远程的新分支?

时间:2014-04-10 07:52:41

标签: c# git libgit2sharp

我想使用libgit2sharp在git上创建和删除分支。我想出了这段代码,但它在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 branch 'buggy-3' ("refs/heads/buggy-3") that you are trying to push does not track an upstream branch.

我尝试在互联网上搜索此错误,但我找不到解决方案可以解决问题。是否可以使用libgit2sharp执行此操作?

1 个答案:

答案 0 :(得分:17)

您必须将本地分支与您想要推送的遥控器相关联。

例如,给定已存在的"origin"遥控器:

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);

注意:: Push()公开其他 overloads ,允许您动态提供此类信息,而无需将其存储在配置中。