我正在尝试在C#中执行以下操作:
我正在运行的当前git命令:
git checkout branch2
git diff branch1 > delta.patch
git checkout --orphan delta_branch
git rm -rf .
git apply delta.patch
git add -A
git commit -m "Adding a temporary branch.."
git push -u origin delta_branch
虽然这可以从git bash中正常工作,但是当它从C#执行时它没有,我得到diff命令的以下消息:
git diff branch1 > delta.patch
编辑:
我用来运行上述每个命令的C#方法如下:
public void ExecuteGitCommand(string sourceDirectory, string gitExePath, string command)
{
ProcessStartInfo gitInfo = new ProcessStartInfo();
gitInfo.CreateNoWindow = true;
gitInfo.RedirectStandardError = true;
gitInfo.RedirectStandardOutput = true;
gitInfo.FileName = gitExePath;
gitInfo.UseShellExecute = false;
Process gitProcess = new Process();
gitInfo.Arguments = command;
gitInfo.WorkingDirectory = sourceDirectory;
gitProcess.StartInfo = gitInfo;
gitProcess.Start();
string output;
string error;
using (StreamReader streamReader = gitProcess.StandardOutput)
{
output = streamReader.ReadToEnd();
}
using (StreamReader streamReader = gitProcess.StandardError)
{
error = streamReader.ReadToEnd();
}
Console.WriteLine("Output:");
Console.WriteLine(output);
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("Error:");
Console.WriteLine(error);
}
gitProcess.WaitForExit();
gitProcess.Close();
}
它被称为:
string[] commands = new string[] { gitCheckout, gitDiff, gitCheckoutDelta, gitRmDeltaFiles, gitApplyPatch, gitAdd, gitCommit, gitPush };
foreach(string command in commands)
{
Console.WriteLine(command); //debug only
ExecuteGitCommand(sourceDirectory, gitExePath, command);
}
注意:我在项目的其他部分使用LibGit2Sharp,但在这种特定情况下我无法使用它,因为LibGit2Sharp没有实现git-apply。
答案 0 :(得分:2)
您不能简单地重定向到Process.Start
信息中的文件。这是一个 shell 操作,而不是你可以简单地调用的东西。相反,您需要自己阅读git
应用程序的标准输出。例如:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = "git.exe";
startInfo.Arguments = "diff branch1";
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
while ((line = process.StandardOutput.ReadLine()) != null)
{
// This is the output you're reading...
}