|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Text; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | + |
| 5 | +namespace DotNetMcp; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Helper class for executing dotnet CLI commands. |
| 9 | +/// Provides a centralized implementation to avoid code duplication between tools and resources. |
| 10 | +/// </summary> |
| 11 | +public static class DotNetCommandExecutor |
| 12 | +{ |
| 13 | + private const int MaxOutputCharacters = 1_000_000; |
| 14 | + private static readonly int NewLineLength = Environment.NewLine.Length; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Execute a dotnet command with full output handling, logging, and truncation support. |
| 18 | + /// </summary> |
| 19 | + /// <param name="arguments">The command-line arguments to pass to dotnet.exe</param> |
| 20 | + /// <param name="logger">Optional logger for debug/warning messages</param> |
| 21 | + /// <returns>Combined output, error, and exit code information</returns> |
| 22 | + public static async Task<string> ExecuteCommandAsync(string arguments, ILogger? logger = null) |
| 23 | + { |
| 24 | + logger?.LogDebug("Executing: dotnet {Arguments}", arguments); |
| 25 | + |
| 26 | + var psi = new ProcessStartInfo |
| 27 | + { |
| 28 | + FileName = "dotnet", |
| 29 | + Arguments = arguments, |
| 30 | + RedirectStandardOutput = true, |
| 31 | + RedirectStandardError = true, |
| 32 | + UseShellExecute = false, |
| 33 | + CreateNoWindow = true |
| 34 | + }; |
| 35 | + |
| 36 | + using var process = new Process { StartInfo = psi }; |
| 37 | + var output = new StringBuilder(); |
| 38 | + var error = new StringBuilder(); |
| 39 | + var outputTruncated = false; |
| 40 | + var errorTruncated = false; |
| 41 | + |
| 42 | + process.OutputDataReceived += (_, e) => |
| 43 | + { |
| 44 | + if (e.Data != null) |
| 45 | + { |
| 46 | + // Check if adding this line would exceed the limit |
| 47 | + int projectedLength = output.Length + e.Data.Length + NewLineLength; |
| 48 | + if (projectedLength < MaxOutputCharacters) |
| 49 | + { |
| 50 | + output.AppendLine(e.Data); |
| 51 | + } |
| 52 | + else if (!outputTruncated) |
| 53 | + { |
| 54 | + output.AppendLine("[Output truncated - exceeded maximum character limit]"); |
| 55 | + outputTruncated = true; |
| 56 | + } |
| 57 | + } |
| 58 | + }; |
| 59 | + |
| 60 | + process.ErrorDataReceived += (_, e) => |
| 61 | + { |
| 62 | + if (e.Data != null) |
| 63 | + { |
| 64 | + // Check if adding this line would exceed the limit |
| 65 | + int projectedLength = error.Length + e.Data.Length + NewLineLength; |
| 66 | + if (projectedLength < MaxOutputCharacters) |
| 67 | + { |
| 68 | + error.AppendLine(e.Data); |
| 69 | + } |
| 70 | + else if (!errorTruncated) |
| 71 | + { |
| 72 | + error.AppendLine("[Error output truncated - exceeded maximum character limit]"); |
| 73 | + errorTruncated = true; |
| 74 | + } |
| 75 | + } |
| 76 | + }; |
| 77 | + |
| 78 | + process.Start(); |
| 79 | + process.BeginOutputReadLine(); |
| 80 | + process.BeginErrorReadLine(); |
| 81 | + await process.WaitForExitAsync(); |
| 82 | + |
| 83 | + logger?.LogDebug("Command completed with exit code: {ExitCode}", process.ExitCode); |
| 84 | + if (outputTruncated) |
| 85 | + { |
| 86 | + logger?.LogWarning("Output was truncated due to size limit"); |
| 87 | + } |
| 88 | + if (errorTruncated) |
| 89 | + { |
| 90 | + logger?.LogWarning("Error output was truncated due to size limit"); |
| 91 | + } |
| 92 | + |
| 93 | + var result = new StringBuilder(); |
| 94 | + if (output.Length > 0) result.AppendLine(output.ToString()); |
| 95 | + if (error.Length > 0) |
| 96 | + { |
| 97 | + result.AppendLine("Errors:"); |
| 98 | + result.AppendLine(error.ToString()); |
| 99 | + } |
| 100 | + result.AppendLine($"Exit Code: {process.ExitCode}"); |
| 101 | + return result.ToString(); |
| 102 | + } |
| 103 | + |
| 104 | + /// <summary> |
| 105 | + /// Execute a dotnet command and return only the standard output. |
| 106 | + /// Throws an exception if the command fails with a non-zero exit code. |
| 107 | + /// </summary> |
| 108 | + /// <param name="arguments">The command-line arguments to pass to dotnet.exe</param> |
| 109 | + /// <param name="logger">Optional logger for debug messages</param> |
| 110 | + /// <returns>Standard output only (no error or exit code information)</returns> |
| 111 | + /// <exception cref="InvalidOperationException">Thrown if the command fails</exception> |
| 112 | + public static async Task<string> ExecuteCommandForResourceAsync(string arguments, ILogger? logger = null) |
| 113 | + { |
| 114 | + logger?.LogDebug("Executing: dotnet {Arguments}", arguments); |
| 115 | + |
| 116 | + var startInfo = new ProcessStartInfo |
| 117 | + { |
| 118 | + FileName = "dotnet", |
| 119 | + Arguments = arguments, |
| 120 | + RedirectStandardOutput = true, |
| 121 | + RedirectStandardError = true, |
| 122 | + UseShellExecute = false, |
| 123 | + CreateNoWindow = true |
| 124 | + }; |
| 125 | + |
| 126 | + using var process = Process.Start(startInfo); |
| 127 | + if (process == null) |
| 128 | + { |
| 129 | + throw new InvalidOperationException($"Failed to start dotnet process with arguments: {arguments}"); |
| 130 | + } |
| 131 | + |
| 132 | + var output = await process.StandardOutput.ReadToEndAsync(); |
| 133 | + var error = await process.StandardError.ReadToEndAsync(); |
| 134 | + await process.WaitForExitAsync(); |
| 135 | + |
| 136 | + if (process.ExitCode != 0) |
| 137 | + { |
| 138 | + logger?.LogError("Command failed with exit code {ExitCode}: {Error}", process.ExitCode, error); |
| 139 | + var errorMessage = !string.IsNullOrEmpty(error) |
| 140 | + ? $"dotnet command failed: {error}" |
| 141 | + : $"dotnet command failed with exit code {process.ExitCode} and no error output."; |
| 142 | + throw new InvalidOperationException(errorMessage); |
| 143 | + } |
| 144 | + |
| 145 | + logger?.LogDebug("Command completed successfully"); |
| 146 | + return output; |
| 147 | + } |
| 148 | +} |
0 commit comments