summary refs log tree commit diff
path: root/LibSystemdCli/CommandExecutor.cs
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2024-01-20 08:34:32 +0100
committerRory& <root@rory.gay>2024-01-20 08:34:32 +0100
commit43e06f4b1b7ead9f8cc97fe547eb49d51f341486 (patch)
treeb700ba441320e0f3944c398080cadd296f03ef07 /LibSystemdCli/CommandExecutor.cs
downloadSystemdCtl-43e06f4b1b7ead9f8cc97fe547eb49d51f341486.tar.xz
Initial commit
Diffstat (limited to 'LibSystemdCli/CommandExecutor.cs')
-rw-r--r--LibSystemdCli/CommandExecutor.cs59
1 files changed, 59 insertions, 0 deletions
diff --git a/LibSystemdCli/CommandExecutor.cs b/LibSystemdCli/CommandExecutor.cs
new file mode 100644
index 0000000..096f1c1
--- /dev/null
+++ b/LibSystemdCli/CommandExecutor.cs
@@ -0,0 +1,59 @@
+using System.Diagnostics;
+
+namespace LibSystemdCli;
+
+public class CommandExecutor
+{
+    public static async Task<string> ExecuteCommand(string command, string args)
+    {
+        Console.WriteLine($"[{DateTime.Now:O}] Executing command: {command} {args}");
+        var process = new Process
+        {
+            StartInfo =
+            {
+                FileName = command,
+                Arguments = args,
+                RedirectStandardOutput = true,
+                RedirectStandardError = true,
+                UseShellExecute = false
+            }
+        };
+        process.Start();
+        var output = await process.StandardOutput.ReadToEndAsync();
+        var error = await process.StandardError.ReadToEndAsync();
+        await process.WaitForExitAsync();
+        if (process.ExitCode != 0)
+        {
+            throw new Exception($"Command {command} {args} failed with exit code {process.ExitCode} and error: {error}");
+        }
+        
+        return output;
+    }
+    
+    public static async IAsyncEnumerable<string> ExecuteCommandAsync(string command, string args)
+    {
+        Console.WriteLine($"[{DateTime.Now:O}] Executing command asynchronously: {command} {args}");
+        var process = new Process
+        {
+            StartInfo =
+            {
+                FileName = command,
+                Arguments = args,
+                RedirectStandardOutput = true,
+                RedirectStandardError = true,
+                UseShellExecute = false
+            }
+        };
+        process.Start();
+        while (!process.StandardOutput.EndOfStream)
+        {
+            var line = await process.StandardOutput.ReadLineAsync();
+            yield return line;
+        }
+        await process.WaitForExitAsync();
+        if (process.ExitCode != 0)
+        {
+            throw new Exception($"Command {command} {args} failed with exit code {process.ExitCode}");
+        }
+    }
+}
\ No newline at end of file