我设法让您的解决方案进行了一些小的修改。我在此处粘贴示例代码以使用 git 凭据进行推送。它使用已存储在计算机中的凭据工作,并在第一次使用 UI 时提示输入凭据。
到目前为止,我遇到的唯一问题是当用户提示输入凭据并且他们输入了无效的用户/密码时。Git 写入控制台询问用户/通行证,直到您输入该过程才完成。试图监控 StandardError/Output 没有成功。我在 stderror 中得到错误文本,但只有在手动填写之后。
public void PushLibGit2Sharp(string repositoryFolder, string branch)
{
using (var repo = new Repository(repositoryFolder))
{
var options = new PushOptions
{
CredentialsProvider = (url, usernameFromUrl, types) =>
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "git.exe",
Arguments = "credential fill",
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process process = new Process
{
StartInfo = startInfo
};
process.Start();
// Write query to stdin.
// For stdin to work we need to send \n instead of WriteLine
// We need to send empty line at the end
var uri = new Uri(url);
process.StandardInput.NewLine = "\n";
process.StandardInput.WriteLine($"protocol={uri.Scheme}");
process.StandardInput.WriteLine($"host={uri.Host}");
process.StandardInput.WriteLine($"path={uri.AbsolutePath}");
process.StandardInput.WriteLine();
// Get user/pass from stdout
string username = null;
string password = null;
string line;
while ((line = process.StandardOutput.ReadLine()) != null)
{
string[] details = line.Split('=');
if (details[0] == "username")
{
username = details[1];
}
else if (details[0] == "password")
{
password = details[1];
}
}
return new UsernamePasswordCredentials()
{
Username = username,
Password = password
};
}
};
repo.Network.Push(repo.Branches[branch], options);
}
}