如何在不需要提供用户详细信息的情况下从特定的远程分支中提取最新信息?

naw*_*fal 5 c# git pull git-pull libgit2sharp

要求:

使用libgit2sharp我想从一个特定的 git 远程分支拉(fetch + merge)最新到我当前签出的本地分支,而不必传递任何其他参数,比如用户凭据等。基本上我试图复制git pull origin my-remote-branch

细节:

我想从 C# 自动化某些 Git 操作。我可以通过调用git.exe(如果我知道路径)简单地做我想做的事,比如git.exe --git-dir=my-repo-directory pull origin my-remote-branch. 请注意,这里我必须提供的唯一外部参数是my-repo-directorymy-remote-branch。Git 让一切都正确,比如姓名、密码、电子邮件、当前工作分支(即使它没有远程连接),而 git pull 就可以正常工作。我不必手动传递任何这些参数。我假设 Git 从 repo 的当前 Git 设置中获取它们(来自 %HOME% 文件夹?)。

有没有办法在 LibGit2Sharp 中模拟它?

我试过的:

using (var repo = new Repository("my-repo-directory"))
{
    PullOptions pullOptions = new PullOptions()
    {
        MergeOptions = new MergeOptions()
        {
            FastForwardStrategy = FastForwardStrategy.Default
        }
    };

    MergeResult mergeResult = Commands.Pull(
        repo,
        new Signature("my name", "my email", DateTimeOffset.Now), // I dont want to provide these
        pullOptions
    );
}
Run Code Online (Sandbox Code Playgroud)

哪个失败,因为它说there is no tracking branch。我不一定需要跟踪远程分支。我只想从特定的随机远程存储库中获取最新信息,并在可能的情况下执行自动合并。

只是为了看看它是否有效,我试过:

using (var repo = new Repository("my-repo-directory"))
{
    var trackingBranch = repo.Branches["remotes/origin/my-remote-branch"];

    if (trackingBranch.IsRemote) // even though I dont want to set tracking branch like this
    {
        var branch = repo.Head;
        repo.Branches.Update(branch, b => b.TrackedBranch = trackingBranch.CanonicalName);
    }

    PullOptions pullOptions = new PullOptions()
    {
        MergeOptions = new MergeOptions()
        {
            FastForwardStrategy = FastForwardStrategy.Default
        }
    };

    MergeResult mergeResult = Commands.Pull(
        repo,
        new Signature("my name", "my email", DateTimeOffset.Now),
        pullOptions
    );
}
Run Code Online (Sandbox Code Playgroud)

这失败了

请求失败,状态码:401

附加信息:

我不想直接调用 git.exe,因为我无法对 git exe 路径进行硬编码。另外,由于我无法在运行时传递用户名、电子邮件等,libgit2sharp 有没有办法从存储库设置中自行获取它们,就像 git.exe 那样?

Von*_*onC 7

我假设 Git 从 repo 的当前 Git 设置中获取它们(来自%HOME%文件夹?)。

这完全取决于远程“起源”是什么:

看到这里的一个UsernamePasswordCredentials例子。
另见LibGit2Sharp.Tests/TestHelpers/Constants.cs其他事件


关于 pull 操作,它涉及一个CommandFetch,它涉及一个refspec。正如在“具有 refspec 差异的 Git pull/fetch ”中一样,您可以source:destination为 pull传递分支名称(即使没有跟踪信息)。

这就是LibGit2Sharp.Tests/FetchFixture.cs.

string refSpec = string.Format("refs/heads/{2}:refs/remotes/{0}/{1}", remoteName, localBranchName, remoteBranchName);
Commands.Fetch(repo, remoteName, new string[] { refSpec }, new FetchOptions {
                TagFetchMode = TagFetchMode.None,
                OnUpdateTips = expectedFetchState.RemoteUpdateTipsHandler
}, null);
Run Code Online (Sandbox Code Playgroud)