Skip to content

Commit f750eb8

Browse files
committed
refactor: Clean up command runner and return all output
1 parent 6e194ab commit f750eb8

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

Git/Project.cs

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -129,45 +129,43 @@ public void SetBranchRef(string branch, string reference)
129129
RunCommand($"branch -f {branch} {reference}");
130130
}
131131

132-
void RunCommand(string command)
132+
void RunCommand(string arguments)
133133
{
134-
foreach (var line in GetCommandOutput(command, true))
134+
foreach (var line in GetCommandOutput(arguments, true))
135135
{
136136
}
137137
}
138138

139-
IEnumerable<string> GetCommandOutput(string command, bool printOutput = false)
139+
IEnumerable<string> GetCommandOutput(string arguments, bool printOutput = false)
140140
{
141-
var args = $"--no-pager {command}";
141+
arguments = $"--no-pager {arguments}";
142142
if (printOutput)
143-
Console.WriteLine($" > git {args}");
143+
Console.WriteLine($" > git {arguments}");
144+
var lines = new List<string>();
144145
var git = new Process();
145146
git.StartInfo.WorkingDirectory = GitPath;
146147
git.StartInfo.FileName = "git";
147-
git.StartInfo.Arguments = args;
148+
git.StartInfo.Arguments = arguments;
148149
git.StartInfo.UseShellExecute = false;
149150
git.StartInfo.RedirectStandardOutput = true;
150151
git.StartInfo.RedirectStandardError = true;
151152
git.StartInfo.StandardOutputEncoding = Encoding.UTF8;
152153
git.StartInfo.StandardErrorEncoding = Encoding.UTF8;
153-
git.ErrorDataReceived += (sender, e) =>
154-
{
155-
if (e.Data?.Length > 0)
156-
Console.Error.WriteLine($" ! {e.Data}");
157-
};
154+
git.OutputDataReceived += (sender, e) => lines.Add($" < {e.Data}");
155+
git.ErrorDataReceived += (sender, e) => lines.Add($" ! {e.Data}");
158156
git.Start();
157+
git.BeginOutputReadLine();
159158
git.BeginErrorReadLine();
160-
while (!git.StandardOutput.EndOfStream)
159+
git.WaitForExit();
160+
foreach (var line in lines)
161161
{
162-
if (printOutput)
163-
Console.WriteLine($" < {git.StandardOutput.ReadLine()}");
164-
else
165-
yield return git.StandardOutput.ReadLine();
162+
if (printOutput && line.Length > 4)
163+
Console.WriteLine(line);
164+
yield return line[4..];
166165
}
167-
git.WaitForExit();
168166
if (git.ExitCode != 0)
169167
{
170-
throw new ApplicationException($"git {command} failed: {git.ExitCode}");
168+
throw new ApplicationException($"git {arguments} failed: {git.ExitCode}");
171169
}
172170
}
173171
}

0 commit comments

Comments
 (0)