如何使用libgit2sharp从本地创建一个新分支并推送到远程?

13

我想使用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个回答

26

您需要将本地分支与要推送的远程分支进行关联。

例如,假设已经存在一个名为"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()会暴露出其他重载,让您能够在不将信息存储在配置文件中的情况下动态提供该信息。


请参考这个 **SO answer**,它应该会为您提供有关分支配置的更多详细信息。 - nulltoken
localReporepo之间有什么区别? - BendEg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接