|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using System.Diagnostics; |
| 5 | +using Cocona; |
| 6 | + |
| 7 | + |
| 8 | +namespace Rephidock.CLI.RunWithColor; |
| 9 | + |
| 10 | + |
| 11 | +public class RunWithColorApp : CoconaLiteConsoleAppBase { |
| 12 | + |
| 13 | + |
| 14 | + [PrimaryCommand] |
| 15 | + public async Task<int> MainAssync( |
| 16 | + [Argument(Description = "Commands and it's arguments (arg0 being the command)", Name="arg")] |
| 17 | + params string[] command |
| 18 | + ) { |
| 19 | + |
| 20 | + // Check for os |
| 21 | + if (!OperatingSystem.IsWindows()) { |
| 22 | + Console.WriteLine("Only windows is supported."); |
| 23 | + return 1; |
| 24 | + } |
| 25 | + |
| 26 | + // Process arguments |
| 27 | + static string QuoteArgumentIfNeeded(string arg) { |
| 28 | + |
| 29 | + // Do not quote arguments which dont contain delimiters |
| 30 | + if (!arg.Contains(' ')) return arg; |
| 31 | + |
| 32 | + // Do not quote arguments which are quoted |
| 33 | + if (arg[0] == '\"' && arg[^1] == '\"') return arg; |
| 34 | + |
| 35 | + // Quote other arguments |
| 36 | + return $"\"{arg}\""; |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + // Define the process |
| 41 | + using Process process = new(); |
| 42 | + process.StartInfo = new ProcessStartInfo { |
| 43 | + UseShellExecute = false, |
| 44 | + FileName = "cmd.exe", |
| 45 | + Arguments = "/C " + string.Join(' ', command.Select(QuoteArgumentIfNeeded)), |
| 46 | + WorkingDirectory = Environment.CurrentDirectory |
| 47 | + }; |
| 48 | + |
| 49 | + // Start the process |
| 50 | + bool hasStarted = process.Start(); |
| 51 | + if (!hasStarted) { |
| 52 | + Console.WriteLine($"Process \"{command}\" could not be started."); |
| 53 | + return 1; |
| 54 | + } |
| 55 | + |
| 56 | + // Set console mode |
| 57 | + bool hasSetColored = NativeCalls.SetVirtualTerminalOutput(true); |
| 58 | + if (!hasSetColored) { |
| 59 | + process.Close(); |
| 60 | + Console.WriteLine($"Could not enable colors. Native error code: {NativeCalls.GetLastErrorCode()}"); |
| 61 | + return 1; |
| 62 | + } |
| 63 | + |
| 64 | + // Wait for it finish |
| 65 | + await process.WaitForExitAsync(); |
| 66 | + return process.ExitCode; |
| 67 | + } |
| 68 | + |
| 69 | +} |
0 commit comments