### Quick Start: Run a Command Source: https://github.com/adamralph/simple-exec/blob/main/README.md A basic example demonstrating how to run an external command with arguments using SimpleExec. ```csharp using static SimpleExec.Command; Run("foo", "arg1 arg2"); ``` -------------------------------- ### Record Exit Code with Custom Handling Source: https://github.com/adamralph/simple-exec/blob/main/README.md Example of using the `handleExitCode` delegate to capture and record the exit code for further analysis, specifically for Robocopy scenarios. ```csharp var exitCode = 0; Run("ROBOCOPY", "from to", handleExitCode: code => (exitCode = code) < 8); // see https://ss64.com/nt/robocopy-exit.html var oneOrMoreFilesCopied = exitCode & 1; var extraFilesOrDirectoriesDetected = exitCode & 2; var misMatchedFilesOrDirectoriesDetected = exitCode & 4; ``` -------------------------------- ### Run Commands with SimpleExec Source: https://github.com/adamralph/simple-exec/blob/main/README.md Demonstrates various ways to run external commands synchronously and asynchronously, including passing arguments as strings or arrays. ```csharp Run("foo"); Run("foo", "arg1 arg2"); Run("foo", new[] { "arg1", "arg2" }); await RunAsync("foo"); await RunAsync("foo", "arg1 arg2"); await RunAsync("foo", new[] { "arg1", "arg2" }); ``` -------------------------------- ### Handle Non-Zero Exit Codes with Robocopy Source: https://github.com/adamralph/simple-exec/blob/main/README.md Illustrates how to use the `handleExitCode` delegate to suppress exceptions for specific non-zero exit codes, as demonstrated with Robocopy. ```csharp Run("ROBOCOPY", "from to", handleExitCode: code => code < 8); ``` -------------------------------- ### Read Command Output with SimpleExec Source: https://github.com/adamralph/simple-exec/blob/main/README.md Shows how to asynchronously read both standard output and standard error from an executed command. Arguments can be passed as strings or arrays. ```csharp var (standardOutput1, standardError1) = await ReadAsync("foo"); var (standardOutput2, standardError2) = await ReadAsync("foo", "arg1 arg2"); var (standardOutput3, standardError3) = await ReadAsync("foo", new[] { "arg1", "arg2" }); ``` -------------------------------- ### Run Source: https://github.com/adamralph/simple-exec/blob/main/SimpleExecTests/PublicApi.IsVerified.verified.txt Runs an external process synchronously. This overload accepts a collection of arguments. ```APIDOC ## Run ### Description Runs an external process synchronously. ### Method Signature ```csharp public static void Run(string name, IEnumerable args, string workingDirectory = "", Action>? configureEnvironment = null, IEnumerable? secrets = null, Func? handleExitCode = null, string? echoPrefix = null, bool noEcho = false, bool cancellationIgnoresProcessTree = false, bool createNoWindow = false, CancellationToken ct = default) ``` ### Parameters * **name** (string) - The name of the executable to run. * **args** (IEnumerable) - A collection of arguments to pass to the executable. * **workingDirectory** (string, optional) - The working directory for the process. Defaults to the current directory. * **configureEnvironment** (Action>?, optional) - An action to configure the environment variables for the process. * **secrets** (IEnumerable?, optional) - A collection of secrets to be made available as environment variables. * **handleExitCode** (Func?, optional) - A function to handle the exit code of the process. If it returns false, an ExitCodeException will be thrown. * **echoPrefix** (string?, optional) - A prefix to prepend to each line of output when echo is enabled. * **noEcho** (bool, optional) - If true, suppresses echoing of the command and its output. Defaults to false. * **cancellationIgnoresProcessTree** (bool, optional) - If true, cancellation will not attempt to terminate child processes. Defaults to false. * **createNoWindow** (bool, optional) - If true, creates the process without a console window. Defaults to false. * **ct** (CancellationToken, optional) - A cancellation token to observe for cancellation requests. Defaults to CancellationToken.None. ### Returns None. The method completes when the process exits. ``` -------------------------------- ### Run (string args) Source: https://github.com/adamralph/simple-exec/blob/main/SimpleExecTests/PublicApi.IsVerified.verified.txt Runs an external process synchronously. This overload accepts a single string for arguments. ```APIDOC ## Run (string args) ### Description Runs an external process synchronously. ### Method Signature ```csharp public static void Run(string name, string args = "", string workingDirectory = "", Action>? configureEnvironment = null, IEnumerable? secrets = null, Func? handleExitCode = null, string? echoPrefix = null, bool noEcho = false, bool cancellationIgnoresProcessTree = false, bool createNoWindow = false, CancellationToken ct = default) ``` ### Parameters * **name** (string) - The name of the executable to run. * **args** (string, optional) - The arguments to pass to the executable as a single string. Defaults to an empty string. * **workingDirectory** (string, optional) - The working directory for the process. Defaults to the current directory. * **configureEnvironment** (Action>?, optional) - An action to configure the environment variables for the process. * **secrets** (IEnumerable?, optional) - A collection of secrets to be made available as environment variables. * **handleExitCode** (Func?, optional) - A function to handle the exit code of the process. If it returns false, an ExitCodeException will be thrown. * **echoPrefix** (string?, optional) - A prefix to prepend to each line of output when echo is enabled. * **noEcho** (bool, optional) - If true, suppresses echoing of the command and its output. Defaults to false. * **cancellationIgnoresProcessTree** (bool, optional) - If true, cancellation will not attempt to terminate child processes. Defaults to false. * **createNoWindow** (bool, optional) - If true, creates the process without a console window. Defaults to false. * **ct** (CancellationToken, optional) - A cancellation token to observe for cancellation requests. Defaults to CancellationToken.None. ### Returns None. The method completes when the process exits. ``` -------------------------------- ### RunAsync (string args) Source: https://github.com/adamralph/simple-exec/blob/main/SimpleExecTests/PublicApi.IsVerified.verified.txt Runs an external process asynchronously. This overload accepts a single string for arguments. ```APIDOC ## RunAsync (string args) ### Description Runs an external process asynchronously. ### Method Signature ```csharp public static Task RunAsync(string name, string args = "", string workingDirectory = "", Action>? configureEnvironment = null, IEnumerable? secrets = null, Func? handleExitCode = null, string? echoPrefix = null, bool noEcho = false, bool cancellationIgnoresProcessTree = false, bool createNoWindow = false, CancellationToken ct = default) ``` ### Parameters * **name** (string) - The name of the executable to run. * **args** (string, optional) - The arguments to pass to the executable as a single string. Defaults to an empty string. * **workingDirectory** (string, optional) - The working directory for the process. Defaults to the current directory. * **configureEnvironment** (Action>?, optional) - An action to configure the environment variables for the process. * **secrets** (IEnumerable?, optional) - A collection of secrets to be made available as environment variables. * **handleExitCode** (Func?, optional) - A function to handle the exit code of the process. If it returns false, an ExitCodeException will be thrown. * **echoPrefix** (string?, optional) - A prefix to prepend to each line of output when echo is enabled. * **noEcho** (bool, optional) - If true, suppresses echoing of the command and its output. Defaults to false. * **cancellationIgnoresProcessTree** (bool, optional) - If true, cancellation will not attempt to terminate child processes. Defaults to false. * **createNoWindow** (bool, optional) - If true, creates the process without a console window. Defaults to false. * **ct** (CancellationToken, optional) - A cancellation token to observe for cancellation requests. Defaults to CancellationToken.None. ### Returns A Task that represents the asynchronous operation. The task completes when the process exits. ``` -------------------------------- ### Run a command synchronously with SimpleExec Source: https://context7.com/adamralph/simple-exec/llms.txt Use `Command.Run` for synchronous execution. Output streams directly to the console. Non-zero exit codes raise `ExitCodeException` by default. Supports various configuration options like working directory, environment variables, echo suppression, custom exit code handling, and cancellation. ```csharp using static SimpleExec.Command; // Minimal usage Run("git", "status"); // With explicit argument list (no escaping needed) Run("git", new[] { "commit", "-m", "feat: add feature" }); // With working directory and environment variable Run( "dotnet", "build", workingDirectory: "/path/to/project", configureEnvironment: env => env["DOTNET_ENVIRONMENT"] = "Production"); // Suppress echo to stdout Run("make", "clean", noEcho: true); // Custom echo prefix Run("npm", "install", echoPrefix: ">> build"); // Handle exit code to avoid exception for known non-zero success codes (e.g., Robocopy) Run("ROBOCOPY", "src dst", handleExitCode: code => code < 8); // Record the exit code while suppressing exception for handled values var exitCode = 0; Run("ROBOCOPY", "src dst", handleExitCode: code => (exitCode = code) < 8); Console.WriteLine($"Files copied: {exitCode & 1}"); // With cancellation token using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Run("long-running-tool", ct: cts.Token); ``` -------------------------------- ### Configure Environment Variables for Child Processes Source: https://context7.com/adamralph/simple-exec/llms.txt Use the `configureEnvironment` delegate to add, override, or remove environment variables for child processes. This is useful for setting up specific configurations or passing data to the executed command. ```csharp using static SimpleExec.Command; // Add or override an environment variable await RunAsync( "dotnet", "run", configureEnvironment: env => { env["ASPNETCORE_ENVIRONMENT"] = "Staging"; env["ConnectionStrings__Default"] = "Server=staging-db;..." ; }); // Remove a variable from the child's environment Run( "some-tool", configureEnvironment: env => env.Remove("PROXY_URL")); // Capture output that depends on an injected env var var (output, _) = await Command.ReadAsync( "node", "-e \"console.log(process.env.GREETING)\"", configureEnvironment: env => env["GREETING"] = "Hello, World!"); Console.WriteLine(output.Trim()); // Hello, World! ``` -------------------------------- ### Run Command Source: https://github.com/adamralph/simple-exec/blob/main/README.md Executes an external command. By default, the command is echoed to standard output. ```APIDOC ## Run Command ### Description Executes an external command. By default, the command is echoed to standard output for visibility. ### Method `Run` (synchronous) and `RunAsync` (asynchronous) ### Signature ```csharp public static void Run(string command, string arguments = null, string workingDirectory = null, Action> configureEnvironment = null, IEnumerable secrets = null, Func handleExitCode = null, string echoPrefix = null, bool noEcho = false, bool cancellationIgnoresProcessTree = false, bool createNoWindow = false); public static Task RunAsync(string command, string arguments = null, string workingDirectory = null, Action> configureEnvironment = null, IEnumerable secrets = null, Func handleExitCode = null, string echoPrefix = null, bool noEcho = false, bool cancellationIgnoresProcessTree = false, bool createNoWindow = false, CancellationToken ct = default); ``` ### Parameters **Common Optional Arguments:** - `workingDirectory` (string): The directory in which to start the process. - `configureEnvironment` (Action>): A delegate to configure the environment variables for the process. - `secrets` (IEnumerable): A collection of secrets to be passed to the command. - `handleExitCode` (Func): A delegate to handle non-zero exit codes. Returns `true` if the exit code is handled and default handling should be suppressed, `false` otherwise. - `echoPrefix` (string): A prefix to use when echoing the command. - `noEcho` (bool): If true, the command will not be echoed to standard output. - `cancellationIgnoresProcessTree` (bool): If true, cancellation will not affect the process tree. - `createNoWindow` (bool): If true, the new process will not create a window. - `ct` (CancellationToken): A token to monitor for cancellation requests (for `RunAsync`). ### Examples ```csharp using static SimpleExec.Command; // Synchronous execution Run("foo", "arg1 arg2"); Run("foo", new[] { "arg1", "arg2" }); // Asynchronous execution await RunAsync("foo"); await RunAsync("foo", "arg1 arg2"); await RunAsync("foo", new[] { "arg1", "arg2" }); // Suppressing exit code exceptions for Robocopy Run("ROBOCOPY", "from to", handleExitCode: code => code < 8); ``` ``` -------------------------------- ### Run a command asynchronously with SimpleExec Source: https://context7.com/adamralph/simple-exec/llms.txt Use `Command.RunAsync` for asynchronous execution. Returns a `Task` that completes when the process exits. Supports the same configuration options as `Run`, including secrets redaction, `createNoWindow`, and `cancellationIgnoresProcessTree`. ```csharp using static SimpleExec.Command; // Basic async run await RunAsync("git", "fetch --all"); // Argument list overload (args are not shell-escaped) await RunAsync("docker", new[] { "build", "-t", "my-app:latest", "." }); // With secrets redacted from the echoed command line await RunAsync( "curl", $"https://api.example.com -H \"Authorization: Bearer {apiToken}\"", secrets: new[] { apiToken }); // Output: myapp: curl https://api.example.com -H "Authorization: Bearer ***" // Run without creating a new window (useful in GUI/service contexts) await RunAsync("ffmpeg", "-i input.mp4 output.webm", createNoWindow: true); // Cancellation that leaves child processes running on cancel using var cts = new CancellationTokenSource(); try { await RunAsync( "gradle", "build", cancellationIgnoresProcessTree: true, ct: cts.Token); } catch (TaskCanceledException) { Console.WriteLine("Build was cancelled."); } ``` -------------------------------- ### Command.Run Source: https://context7.com/adamralph/simple-exec/llms.txt Runs an external command synchronously, streaming its output directly to the caller's stdout/stderr. It supports various configuration options like working directory, environment variables, and custom exit code handling. Throws `ExitCodeException` on non-zero exit by default. ```APIDOC ## Command.Run ### Description Runs an external command synchronously, streaming its output directly to the caller's stdout/stderr. Echoes the command line to stdout by default. Throws `ExitCodeException` on non-zero exit. ### Method `Command.Run` ### Parameters - `command` (string) - The command to execute. - `args` (string or string[]) - Arguments for the command. - `workingDirectory` (string, optional) - The working directory for the command. - `configureEnvironment` (Action>, optional) - Configures environment variables for the command. - `noEcho` (bool, optional) - Suppresses echoing the command line to stdout. - `echoPrefix` (string, optional) - Custom prefix for echoed command lines. - `handleExitCode` (Func, optional) - A function to handle specific exit codes, preventing exceptions. - `ct` (CancellationToken, optional) - A token to cancel the operation. ### Request Example ```csharp using static SimpleExec.Command; // Minimal usage Run("git", "status"); // With explicit argument list (no escaping needed) Run("git", new[] { "commit", "-m", "feat: add feature" }); // With working directory and environment variable Run( "dotnet", "build", workingDirectory: "/path/to/project", configureEnvironment: env => env["DOTNET_ENVIRONMENT"] = "Production"); // Suppress echo to stdout Run("make", "clean", noEcho: true); // Custom echo prefix Run("npm", "install", echoPrefix: ">> build"); // Handle exit code to avoid exception for known non-zero success codes (e.g., Robocopy) Run("ROBOCOPY", "src dst", handleExitCode: code => code < 8); // Record the exit code while suppressing exception for handled values var exitCode = 0; Run("ROBOCOPY", "src dst", handleExitCode: code => (exitCode = code) < 8); Console.WriteLine($"Files copied: {exitCode & 1}"); // With cancellation token using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); Run("long-running-tool", ct: cts.Token); ``` ``` -------------------------------- ### RunAsync Source: https://github.com/adamralph/simple-exec/blob/main/SimpleExecTests/PublicApi.IsVerified.verified.txt Runs an external process asynchronously. This overload accepts a collection of arguments. ```APIDOC ## RunAsync ### Description Runs an external process asynchronously. ### Method Signature ```csharp public static Task RunAsync(string name, IEnumerable args, string workingDirectory = "", Action>? configureEnvironment = null, IEnumerable? secrets = null, Func? handleExitCode = null, string? echoPrefix = null, bool noEcho = false, bool cancellationIgnoresProcessTree = false, bool createNoWindow = false, CancellationToken ct = default) ``` ### Parameters * **name** (string) - The name of the executable to run. * **args** (IEnumerable) - A collection of arguments to pass to the executable. * **workingDirectory** (string, optional) - The working directory for the process. Defaults to the current directory. * **configureEnvironment** (Action>?, optional) - An action to configure the environment variables for the process. * **secrets** (IEnumerable?, optional) - A collection of secrets to be made available as environment variables. * **handleExitCode** (Func?, optional) - A function to handle the exit code of the process. If it returns false, an ExitCodeException will be thrown. * **echoPrefix** (string?, optional) - A prefix to prepend to each line of output when echo is enabled. * **noEcho** (bool, optional) - If true, suppresses echoing of the command and its output. Defaults to false. * **cancellationIgnoresProcessTree** (bool, optional) - If true, cancellation will not attempt to terminate child processes. Defaults to false. * **createNoWindow** (bool, optional) - If true, creates the process without a console window. Defaults to false. * **ct** (CancellationToken, optional) - A cancellation token to observe for cancellation requests. Defaults to CancellationToken.None. ### Returns A Task that represents the asynchronous operation. The task completes when the process exits. ``` -------------------------------- ### Capture Command Output with ReadAsync Source: https://context7.com/adamralph/simple-exec/llms.txt Use `Command.ReadAsync` to run external commands and capture their standard output and standard error as strings. It handles non-zero exit codes by throwing `ExitCodeReadException`, which includes captured output. Supports custom encoding, piping input, environment variables, and handling specific exit codes. ```csharp using SimpleExec; // Basic capture var (stdout, stderr) = await Command.ReadAsync("git", "log --oneline -5"); Console.WriteLine(stdout); // Argument list overload (handles spaces in args automatically) var (output, _) = await Command.ReadAsync( "dotnet", new[] { "list", "package", "--outdated" }); // With custom encoding (e.g., reading Unicode output) var (unicodeOut, _) = await Command.ReadAsync( "locale", encoding: new System.Text.UnicodeEncoding()); // Pipe input via stdin var (result, _) = await Command.ReadAsync( "python3", "-c \"import sys; print(sys.stdin.read().upper())\"", standardInput: "hello from .net"); Console.WriteLine(result); // HELLO FROM .NET // Set environment variables var (envOut, _) = await Command.ReadAsync( "printenv", "MY_VAR", configureEnvironment: env => env["MY_VAR"] = "hello"); Console.WriteLine(envOut.Trim()); // hello // Suppress exception for a known non-zero success exit code var (data, _) = await Command.ReadAsync( "diff", "file1.txt file2.txt", handleExitCode: code => code == 1); // diff returns 1 when files differ // With cancellation using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var (json, _) = await Command.ReadAsync("curl", "-s https://api.example.com/data", ct: cts.Token); ``` -------------------------------- ### Command.ReadAsync Source: https://context7.com/adamralph/simple-exec/llms.txt Runs an external command and asynchronously captures both stdout and stderr as strings. It returns a named-tuple containing StandardOutput and StandardError. Throws ExitCodeReadException on non-zero exit codes. ```APIDOC ## Command.ReadAsync ### Description Runs an external command and asynchronously captures both stdout and stderr as strings. Returns a named-tuple `(string StandardOutput, string StandardError)`. Throws `ExitCodeReadException` (which extends `ExitCodeException`) on non-zero exit; the exception includes the captured output. ### Method `Command.ReadAsync(string command, string arguments = "", Encoding? encoding = null, string? standardInput = null, Action>? configureEnvironment = null, Func? handleExitCode = null, CancellationToken ct = default) `Command.ReadAsync(string command, string[] arguments, Encoding? encoding = null, string? standardInput = null, Action>? configureEnvironment = null, Func? handleExitCode = null, CancellationToken ct = default) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // Basic capture var (stdout, stderr) = await Command.ReadAsync("git", "log --oneline -5"); // Argument list overload var (output, _) = await Command.ReadAsync("dotnet", new[] { "list", "package", "--outdated" }); // With custom encoding var (unicodeOut, _) = await Command.ReadAsync("locale", encoding: new System.Text.UnicodeEncoding()); // Pipe input via stdin var (result, _) = await Command.ReadAsync("python3", "-c \"import sys; print(sys.stdin.read().upper())\"", standardInput: "hello from .net"); // Set environment variables var (envOut, _) = await Command.ReadAsync("printenv", "MY_VAR", configureEnvironment: env => env["MY_VAR"] = "hello"); // Suppress exception for a known non-zero success exit code var (data, _) = await Command.ReadAsync("diff", "file1.txt file2.txt", handleExitCode: code => code == 1); // With cancellation using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var (json, _) = await Command.ReadAsync("curl", "-s https://api.example.com/data", ct: cts.Token); ``` ### Response #### Success Response (200) Returns a named-tuple `(string StandardOutput, string StandardError)`. #### Response Example ```json { "StandardOutput": "Captured stdout string", "StandardError": "Captured stderr string" } ``` ### Error Handling Throws `ExitCodeReadException` on non-zero exit codes. ``` -------------------------------- ### Command.RunAsync Source: https://context7.com/adamralph/simple-exec/llms.txt Asynchronously runs an external command, returning a Task that completes when the process exits. It accepts the same optional parameters as `Command.Run` and also throws `ExitCodeException` on non-zero exit. ```APIDOC ## Command.RunAsync ### Description Asynchronous counterpart to `Run`. Returns a `Task` that completes when the process exits. Accepts the same optional parameters. Throws `ExitCodeException` on non-zero exit. ### Method `Command.RunAsync` ### Parameters - `command` (string) - The command to execute. - `args` (string or string[]) - Arguments for the command. - `workingDirectory` (string, optional) - The working directory for the command. - `configureEnvironment` (Action>, optional) - Configures environment variables for the command. - `noEcho` (bool, optional) - Suppresses echoing the command line to stdout. - `echoPrefix` (string, optional) - Custom prefix for echoed command lines. - `handleExitCode` (Func, optional) - A function to handle specific exit codes, preventing exceptions. - `ct` (CancellationToken, optional) - A token to cancel the operation. - `secrets` (IEnumerable, optional) - A collection of secrets to redact from the echoed command line. - `createNoWindow` (bool, optional) - If true, the command runs without creating a new window. - `cancellationIgnoresProcessTree` (bool, optional) - If true, cancellation leaves child processes running. ### Request Example ```csharp using static SimpleExec.Command; // Basic async run await RunAsync("git", "fetch --all"); // Argument list overload (args are not shell-escaped) await RunAsync("docker", new[] { "build", "-t", "my-app:latest", "." }); // With secrets redacted from the echoed command line await RunAsync( "curl", $"https://api.example.com -H \"Authorization: Bearer {apiToken}\"", secrets: new[] { apiToken }); // Output: myapp: curl https://api.example.com -H "Authorization: Bearer ***" // Run without creating a new window (useful in GUI/service contexts) await RunAsync("ffmpeg", "-i input.mp4 output.webm", createNoWindow: true); // Cancellation that leaves child processes running on cancel using var cts = new CancellationTokenSource(); try { await RunAsync( "gradle", "build", cancellationIgnoresProcessTree: true, ct: cts.Token); } catch (TaskCanceledException) { Console.WriteLine("Build was cancelled."); } ``` ``` -------------------------------- ### Read Command Output Source: https://github.com/adamralph/simple-exec/blob/main/README.md Executes an external command and captures its standard output and standard error. ```APIDOC ## Read Command Output ### Description Executes an external command and captures its standard output and standard error. ### Method `ReadAsync` (asynchronous) ### Signature ```csharp public static Task<(string standardOutput, string standardError)> ReadAsync(string command, string arguments = null, string workingDirectory = null, Action> configureEnvironment = null, Func handleExitCode = null, Encoding encoding = null, string standardInput = null, bool cancellationIgnoresProcessTree = false, CancellationToken ct = default); ``` ### Parameters **Common Optional Arguments:** - `workingDirectory` (string): The directory in which to start the process. - `configureEnvironment` (Action>): A delegate to configure the environment variables for the process. - `handleExitCode` (Func): A delegate to handle non-zero exit codes. Returns `true` if the exit code is handled and default handling should be suppressed, `false` otherwise. - `encoding` (Encoding): The encoding to use for reading standard output and standard error. - `standardInput` (string): The string to write to the standard input of the process. - `cancellationIgnoresProcessTree` (bool): If true, cancellation will not affect the process tree. - `ct` (CancellationToken): A token to monitor for cancellation requests. ### Response - `standardOutput` (string): The standard output of the command. - `standardError` (string): The standard error of the command. ### Examples ```csharp using static SimpleExec.Command; var (standardOutput1, standardError1) = await ReadAsync("foo"); var (standardOutput2, standardError2) = await ReadAsync("foo", "arg1 arg2"); var (standardOutput3, standardError3) = await ReadAsync("foo", new[] { "arg1", "arg2" }); ``` ``` -------------------------------- ### ExitCodeException Source: https://context7.com/adamralph/simple-exec/llms.txt Exception thrown by Run and RunAsync when a command exits with a non-zero code that has not been handled. It includes the integer ExitCode. ```APIDOC ## ExitCodeException ### Description Thrown by `Run` and `RunAsync` when a command exits with a non-zero code that has not been handled by `handleExitCode`. Carries the integer `ExitCode`. ### Method `ExitCodeException(int exitCode, string message)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp try { Command.Run("git", "push origin main"); } catch (ExitCodeException ex) { // ex.ExitCode contains the process exit code Console.Error.WriteLine($"git push failed with exit code {ex.ExitCode}"); } try { await Command.RunAsync("npm", "test"); } catch (ExitCodeException ex) when (ex.ExitCode == 1) { Console.Error.WriteLine("Tests failed."); } ``` ### Response #### Success Response (200) N/A (This is an exception class) #### Response Example N/A ### Error Handling N/A ``` -------------------------------- ### ReadAsync (string args) Source: https://github.com/adamralph/simple-exec/blob/main/SimpleExecTests/PublicApi.IsVerified.verified.txt Reads the standard output and standard error of an external process asynchronously. This overload accepts a single string for arguments. ```APIDOC ## ReadAsync (string args) ### Description Reads the standard output and standard error of an external process asynchronously. ### Method Signature ```csharp public static Task> ReadAsync(string name, string args = "", string workingDirectory = "", Action>? configureEnvironment = null, Func? handleExitCode = null, Encoding? encoding = null, string? standardInput = null, bool cancellationIgnoresProcessTree = false, CancellationToken ct = default) ``` ### Parameters * **name** (string) - The name of the executable to run. * **args** (string, optional) - The arguments to pass to the executable as a single string. Defaults to an empty string. * **workingDirectory** (string, optional) - The working directory for the process. Defaults to the current directory. * **configureEnvironment** (Action>?, optional) - An action to configure the environment variables for the process. * **handleExitCode** (Func?, optional) - A function to handle the exit code of the process. If it returns false, an ExitCodeException will be thrown. * **encoding** (Encoding?, optional) - The encoding to use for reading standard output and error. Defaults to UTF-8. * **standardInput** (string?, optional) - The string to write to the standard input of the process. * **cancellationIgnoresProcessTree** (bool, optional) - If true, cancellation will not attempt to terminate child processes. Defaults to false. * **ct** (CancellationToken, optional) - A cancellation token to observe for cancellation requests. Defaults to CancellationToken.None. ### Returns A Task that represents the asynchronous operation. The task result is a ValueTuple containing the standard output and standard error as strings. ``` -------------------------------- ### Handle Non-Zero Exit Codes with ExitCodeException Source: https://context7.com/adamralph/simple-exec/llms.txt Catch `ExitCodeException` when `Command.Run` or `Command.RunAsync` encounters a non-zero exit code. The exception's `ExitCode` property provides the exit code. This can be used to gracefully handle command failures. ```csharp using SimpleExec; try { Command.Run("git", "push origin main"); } catch (ExitCodeException ex) { // ex.ExitCode contains the process exit code // ex.Message: "The command exited with code 1." Console.Error.WriteLine($"git push failed with exit code {ex.ExitCode}"); Environment.Exit(ex.ExitCode); } // Check for specific exit codes try { await Command.RunAsync("npm", "test"); } catch (ExitCodeException ex) when (ex.ExitCode == 1) { Console.Error.WriteLine("Tests failed."); } ``` -------------------------------- ### ExitCodeException Message Format Source: https://github.com/adamralph/simple-exec/blob/main/README.md The standard message format for an `ExitCodeException` when a command returns a non-zero exit code. ```csharp $"The command exited with code {ExitCode}." ``` -------------------------------- ### Handle Non-Zero Exit Codes with ExitCodeReadException Source: https://context7.com/adamralph/simple-exec/llms.txt When `Command.ReadAsync` fails with a non-zero exit code, `ExitCodeReadException` is thrown. This exception inherits from `ExitCodeException` and additionally provides `StandardOutput` and `StandardError` properties containing the captured output up to the point of failure. ```csharp using SimpleExec; try { var (stdout, _) = await Command.ReadAsync("dotnet", "build /p:TreatWarningsAsErrors=true"); Console.WriteLine(stdout); } catch (ExitCodeReadException ex) { // ex.ExitCode – the process exit code // ex.StandardOutput – captured stdout // ex.StandardError – captured stderr Console.Error.WriteLine($"Build failed (exit code {ex.ExitCode})"); Console.Error.WriteLine("--- stdout ---"); Console.Error.WriteLine(ex.StandardOutput); Console.Error.WriteLine("--- stderr ---"); Console.Error.WriteLine(ex.StandardError); } // ExitCodeReadException is-a ExitCodeException, so this also works: catch (ExitCodeException ex) { Console.Error.WriteLine($"Command failed: {ex.ExitCode}"); } ``` -------------------------------- ### Cancel Running Processes with CancellationToken Source: https://context7.com/adamralph/simple-exec/llms.txt Pass a `CancellationToken` to `RunAsync` or `ReadAsync` to cancel the operation. By default, this also kills the entire process tree. You can optionally prevent child processes from being killed using `cancellationIgnoresProcessTree: true`. ```csharp using static SimpleExec.Command; // Cancel after a timeout using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); try { await RunAsync("npm", "run build", ct: cts.Token); } catch (TaskCanceledException) { Console.WriteLine("Build timed out."); } // Cancel externally (e.g., Ctrl+C handler) using var cts2 = new CancellationTokenSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; cts2.Cancel(); }; await RunAsync("long-running-process", ct: cts2.Token); // Leave child processes alive when cancelling (cancellationIgnoresProcessTree: true) await RunAsync( "parent-process", cancellationIgnoresProcessTree: true, ct: cts.Token); ``` -------------------------------- ### Redact Secrets from Command Output Source: https://context7.com/adamralph/simple-exec/llms.txt Use the `secrets` parameter with `Run` and `RunAsync` to replace sensitive values (like API keys or passwords) with `***` in the echoed command line, working directory, and echo prefix. This prevents sensitive data from being logged. ```csharp using static SimpleExec.Command; var apiKey = Environment.GetEnvironmentVariable("API_KEY")!; var dbPassword = Environment.GetEnvironmentVariable("DB_PASS")!; // Both secrets are redacted from the console echo await RunAsync( "deploy-tool", $"--api-key {apiKey} --db-pass {dbPassword}", secrets: new[] { apiKey, dbPassword }); // Console output: myapp: deploy-tool --api-key *** --db-pass *** // Works with argument lists too await RunAsync( "vault", new[] { "write", "secret/app", $ ``` -------------------------------- ### ReadAsync Source: https://github.com/adamralph/simple-exec/blob/main/SimpleExecTests/PublicApi.IsVerified.verified.txt Reads the standard output and standard error of an external process asynchronously. This overload accepts a collection of arguments. ```APIDOC ## ReadAsync ### Description Reads the standard output and standard error of an external process asynchronously. ### Method Signature ```csharp public static Task> ReadAsync(string name, IEnumerable args, string workingDirectory = "", Action>? configureEnvironment = null, Func? handleExitCode = null, Encoding? encoding = null, string? standardInput = null, bool cancellationIgnoresProcessTree = false, CancellationToken ct = default) ``` ### Parameters * **name** (string) - The name of the executable to run. * **args** (IEnumerable) - A collection of arguments to pass to the executable. * **workingDirectory** (string, optional) - The working directory for the process. Defaults to the current directory. * **configureEnvironment** (Action>?, optional) - An action to configure the environment variables for the process. * **handleExitCode** (Func?, optional) - A function to handle the exit code of the process. If it returns false, an ExitCodeException will be thrown. * **encoding** (Encoding?, optional) - The encoding to use for reading standard output and error. Defaults to UTF-8. * **standardInput** (string?, optional) - The string to write to the standard input of the process. * **cancellationIgnoresProcessTree** (bool, optional) - If true, cancellation will not attempt to terminate child processes. Defaults to false. * **ct** (CancellationToken, optional) - A cancellation token to observe for cancellation requests. Defaults to CancellationToken.None. ### Returns A Task that represents the asynchronous operation. The task result is a ValueTuple containing the standard output and standard error as strings. ``` -------------------------------- ### ExitCodeReadException Source: https://context7.com/adamralph/simple-exec/llms.txt Exception thrown by ReadAsync when the command exits with an unhandled non-zero code. It inherits from ExitCodeException and adds StandardOutput and StandardError string properties. ```APIDOC ## ExitCodeReadException ### Description Thrown by `ReadAsync` when the command exits with an unhandled non-zero code. Inherits from `ExitCodeException` and adds `StandardOutput` and `StandardError` string properties containing all captured output up to the point of failure. ### Method `ExitCodeReadException(int exitCode, string? standardOutput, string? standardError, string message)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp try { var (stdout, _) = await Command.ReadAsync("dotnet", "build /p:TreatWarningsAsErrors=true"); } catch (ExitCodeReadException ex) { // ex.ExitCode – the process exit code // ex.StandardOutput – captured stdout // ex.StandardError – captured stderr Console.Error.WriteLine($"Build failed (exit code {ex.ExitCode})"); Console.Error.WriteLine("--- stdout ---"); Console.Error.WriteLine(ex.StandardOutput); Console.Error.WriteLine("--- stderr ---"); Console.Error.WriteLine(ex.StandardError); } // ExitCodeReadException is-a ExitCodeException, so this also works: catch (ExitCodeException ex) { Console.Error.WriteLine($"Command failed: {ex.ExitCode}"); } ``` ### Response #### Success Response (200) N/A (This is an exception class) #### Response Example N/A ### Error Handling N/A ``` -------------------------------- ### ExitCodeReadException Message Format Source: https://github.com/adamralph/simple-exec/blob/main/README.md The message format for an `ExitCodeReadException` when `ReadAsync` encounters a non-zero exit code, including captured standard output and error. ```csharp $@"The command exited with code {ExitCode}. Standard output: {StandardOutput} Standard error: {StandardError}" ``` -------------------------------- ### Secret Redaction Source: https://context7.com/adamralph/simple-exec/llms.txt Allows hiding sensitive values from echoed output in Run and RunAsync by specifying a collection of secrets to be redacted. ```APIDOC ## Secret Redaction ### Description `Run` and `RunAsync` accept a `secrets` parameter. Any string in that collection is replaced with `***` (case-insensitively) in the echoed command line, working directory path, and echo prefix before it is written to stdout. ### Method `RunAsync(string command, string arguments, IEnumerable secrets, ...)` `RunAsync(string command, string[] arguments, IEnumerable secrets, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using static SimpleExec.Command; var apiKey = Environment.GetEnvironmentVariable("API_KEY")!; var dbPassword = Environment.GetEnvironmentVariable("DB_PASS")!; // Both secrets are redacted from the console echo await RunAsync("deploy-tool", $ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.