Skip to content

Commit 7a7db6e

Browse files
committed
Created the app using Cocona
1 parent f7404b4 commit 7a7db6e

3 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
using Cocona;
2+
using Rephidock.CLI.RunWithColor;
3+
4+
5+
CoconaLiteApp.Run<RunWithColorApp>(args);

src/Rephidock.CLI.RunWithColor/Rephidock.CLI.RunWithColor.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,8 @@
1616
<SelfContained>true</SelfContained>
1717
</PropertyGroup>
1818

19+
<ItemGroup>
20+
<PackageReference Include="Cocona.Lite" Version="2.2.0" />
21+
</ItemGroup>
22+
1923
</Project>
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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

Comments
 (0)