-
Notifications
You must be signed in to change notification settings - Fork 0
/
CommandExecuter.cs
97 lines (72 loc) · 3.1 KB
/
CommandExecuter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace RootsBuilder
{
public class CommandExecuter
{
public static readonly string[] versionCommands = { "--version", "-version", "-v" };
public static void CheckVersion(string command, string version)
{
CommandOutput commandOutput = GetVersion(command);
string outputVersion = Regex.Replace(commandOutput.output.First(), "[^0-9.]", "");
string[] explodedVersion = version.Split(".");
string[] explodedOutputVersion = outputVersion.Split(".");
for (int i = 0; i < explodedVersion.Length; i++)
if (explodedOutputVersion[i] != explodedVersion[i])
throw new Exception($"{command} with a version of {outputVersion} and not {version}");
}
private static CommandOutput GetVersion(string command)
{
CommandOutput commandOutput = new();
for (int i = 0; i < versionCommands.Length; i++)
{
string versionCommand = versionCommands[i];
commandOutput = ExecuteCommand($"{command} {versionCommand}");
if (commandOutput.exitCode.Contains("0"))
break;
}
if (!commandOutput.exitCode.Contains("0"))
throw new Exception($"{command} is not a command with a version descriptor");
return commandOutput;
}
public static CommandOutput ExecuteCommand(string command)
{
CommandOutput commandOutput = new(command);
Console.WriteLine(commandOutput.command);
Process process = Process.Start(CreateProcessInfo(command));
LogStreamAsync(process.StandardOutput, commandOutput.AddOutput);
LogStreamAsync(process.StandardError, commandOutput.AddError);
process.WaitForExit();
LogAndWriteToConsole(commandOutput.AddExitCode, process.ExitCode.ToString());
process.Close();
return commandOutput;
}
private static void LogStreamAsync(StreamReader stream, Func<string, string> LogMethod)
{
Thread thread = new(_ => LogStream(stream, LogMethod));
thread.Start();
}
private static void LogStream(StreamReader stream, Func<string, string> LogMethod)
{
while (!stream.EndOfStream)
{
string output = stream.ReadLine();
LogAndWriteToConsole(LogMethod, output);
}
}
private static void LogAndWriteToConsole(Func<string, string> LogMethod, string output) =>
Console.WriteLine(LogMethod.Invoke(output));
private static ProcessStartInfo CreateProcessInfo(string command) =>
new("cmd.exe", $"/c {command}")
{
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
}
}