### Method Chaining Example Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Demonstrates how to configure and execute a command using the fluent API. ```APIDOC var result = await Cli.Wrap("dotnet") .WithArguments(args => args .Add("build") .Add("-c") .Add("Release") ) .WithWorkingDirectory("/path/to/project") .WithEnvironmentVariables(env => env .Set("BUILD_NUMBER", "42") .Set("COMPILER", "clang") ) .WithValidation(CommandResultValidation.ZeroExitCode) .ExecuteBufferedAsync(); ``` -------------------------------- ### WithCredentials Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Sets the user credentials under which the child process should be started. ```APIDOC ## WithCredentials(creds) ### Description Sets the domain, username, and password for the user context of the child process. ### Parameters - **creds** (Action | Credentials) - Required - The user credentials configuration. ``` -------------------------------- ### Usage Examples for Piping Output Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Demonstrates how to pipe command output to a StringBuilder, a file stream, or an action delegate. ```csharp // Pipe to a string builder var output = new StringBuilder(); var cmd = Cli.Wrap("echo") .WithArguments(["hello"]) | output; // Pipe to a stream var cmd = Cli.Wrap("cat") .WithArguments(["file.txt"]) | File.Create("output.txt"); // Pipe to an action var cmd = Cli.Wrap("ls") | (line => Console.WriteLine(line)); ``` -------------------------------- ### Usage Examples for Piping Input Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Demonstrates piping strings, file streams, and other commands into a command's standard input. ```csharp // Pipe from string var cmd = "hello world" | Cli.Wrap("cat"); // Pipe from file var cmd = File.OpenRead("input.txt") | Cli.Wrap("cat"); // Pipe from another command (chaining) var cmd1 = Cli.Wrap("cat").WithArguments(["input.txt"]); var cmd2 = cmd1 | Cli.Wrap("grep").WithArguments(["pattern"]); ``` -------------------------------- ### Usage Example for Piping stdout and stderr Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Shows how to capture both standard output and standard error into separate StringBuilders. ```csharp var stdOut = new StringBuilder(); var stdErr = new StringBuilder(); var cmd = Cli.Wrap("some-tool") | (stdOut, stdErr); await cmd.ExecuteAsync(); ``` -------------------------------- ### Handle StartedCommandEvent Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Triggered when the command starts. Use this to capture the process ID. ```csharp public class StartedCommandEvent(int processId) : CommandEvent { public int ProcessId { get; } } ``` ```csharp await foreach (var cmdEvent in cmd.ListenAsync()) { if (cmdEvent is StartedCommandEvent started) { Console.WriteLine($"Command started, PID: {started.ProcessId}"); } } ``` -------------------------------- ### Credentials Constructor Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Initializes a new instance of the Credentials class to define user authentication details for starting a process. ```APIDOC ## Credentials(string? domain, string? userName, string? password, bool loadUserProfile) ### Description Represents user credentials used for starting a process. ### Parameters - **domain** (string?) - Optional - Active Directory domain (Windows only) - **userName** (string?) - Optional - Username - **password** (string?) - Optional - Password (Windows only) - **loadUserProfile** (bool) - Optional - Whether to load the user profile (Windows only) ``` -------------------------------- ### PipeTarget.ToDelegate usage Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Examples of using ToDelegate to process command output line-by-line using async or sync delegates. ```csharp var lineCount = 0; await Cli.Wrap("cat") .WithArguments(["large-file.txt"]) .WithStandardOutputPipe(PipeTarget.ToDelegate( async (line, ct) => { lineCount++; Console.WriteLine($"Line {lineCount}: {line}"); await Task.Delay(10, ct); } )) .ExecuteAsync(); ``` ```csharp await Cli.Wrap("git") .WithArguments(["log", "--oneline"]) .WithStandardOutputPipe(PipeTarget.ToDelegate( async line => { await Console.Out.WriteLineAsync(line); } )) .ExecuteAsync(); ``` ```csharp var lines = new List(); await Cli.Wrap("cat") .WithArguments(["input.txt"]) .WithStandardOutputPipe(PipeTarget.ToDelegate( line => lines.Add(line) )) .ExecuteAsync(); ``` -------------------------------- ### SetPassword(string? password) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Sets the password used when starting the process. ```APIDOC ## SetPassword(string? password) ### Description Sets the password used when starting the process. ### Parameters - **password** (string?) - Required - Password or null to clear ### Returns - **CredentialsBuilder** - This builder instance for method chaining. ``` -------------------------------- ### Define StartedCommandEvent Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Represents the start of command execution. This event appears exactly once in the event stream. ```csharp public class StartedCommandEvent(int processId) : CommandEvent { public int ProcessId { get; } } ``` -------------------------------- ### Execute command with full control buffering Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/buffered-execution.md Example usage of the ExecuteBufferedAsync overload requiring explicit encodings and cancellation tokens. ```csharp using CliWrap; using CliWrap.Buffered; var result = await Cli.Wrap("git") .WithArguments(["--version"]) .ExecuteBufferedAsync( Encoding.UTF8, Encoding.UTF8, CancellationToken.None, CancellationToken.None ); Console.WriteLine(result.StandardOutput); ``` -------------------------------- ### Execute command with single token buffering Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/buffered-execution.md Example usage of the ExecuteBufferedAsync overload using a single cancellation token for both graceful and forceful cancellation. ```csharp var result = await Cli.Wrap("echo") .WithArguments(["hello"]) .ExecuteBufferedAsync(Encoding.UTF8, Encoding.UTF8); Console.WriteLine(result.StandardOutput); // "hello" ``` -------------------------------- ### SetUserName(string? userName) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Sets the username used when starting the process. ```APIDOC ## SetUserName(string? userName) ### Description Sets the username used when starting the process. ### Parameters - **userName** (string?) - Required - Username or null to clear ### Returns - **CredentialsBuilder** - This builder instance for method chaining. ``` -------------------------------- ### Consume Command Events Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Example of iterating over command events using an asynchronous foreach loop. ```csharp await foreach (var cmdEvent in Cli.Wrap("ls").ListenAsync()) { switch (cmdEvent) { case StandardOutputCommandEvent stdOut: Console.WriteLine(stdOut.Text); break; } } ``` -------------------------------- ### Add formattable arguments Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Defines the method signatures for adding formattable objects, with an example of usage. ```csharp public ArgumentsBuilder Add( IFormattable value, IFormatProvider formatProvider, bool escape = true ) public ArgumentsBuilder Add(IFormattable value, bool escape) public ArgumentsBuilder Add(IFormattable value) ``` ```csharp var args = new ArgumentsBuilder() .Add("--count") .Add(42) // Numeric values are automatically converted to strings .Build(); ``` -------------------------------- ### LoadUserProfile(bool loadUserProfile) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Instructs whether to load the user profile when starting the process. ```APIDOC ## LoadUserProfile(bool loadUserProfile) ### Description Instructs whether to load the user profile when starting the process. ### Parameters - **loadUserProfile** (bool) - Optional (Default: true) - Whether to load the user profile ### Returns - **CredentialsBuilder** - This builder instance for method chaining. ``` -------------------------------- ### SetDomain(string? domain) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Sets the Active Directory domain used when starting the process. ```APIDOC ## SetDomain(string? domain) ### Description Sets the Active Directory domain used when starting the process. ### Parameters - **domain** (string?) - Required - Domain name or null to clear ### Returns - **CredentialsBuilder** - This builder instance for method chaining. ``` -------------------------------- ### Define Credentials class Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Immutable class used for specifying user credentials when starting a process. ```csharp public partial class Credentials( string? domain = null, string? userName = null, string? password = null, bool loadUserProfile = false ) ``` -------------------------------- ### Process command events with ListenAsync Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Uses a switch expression to handle different command event types like start, output, error, and exit. ```csharp using CliWrap; using CliWrap.EventStream; await foreach (var cmdEvent in Cli.Wrap("git") .WithArguments(["log", "--oneline", "-n", "5"]) .ListenAsync()) { switch (cmdEvent) { case StartedCommandEvent started: Console.WriteLine($"Started (PID: {started.ProcessId})"); break; case StandardOutputCommandEvent stdOut: Console.WriteLine($" {stdOut.Text}"); break; case StandardErrorCommandEvent stdErr: Console.WriteLine($"Error: {stdErr.Text}"); break; case ExitedCommandEvent exited: Console.WriteLine($"Exited ({exited.ExitCode})"); break; } } ``` -------------------------------- ### Compare manual piping and buffered execution Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/buffered-execution.md Demonstrates the difference in complexity between manual pipe configuration and buffered execution. ```csharp var output = new StringBuilder(); var error = new StringBuilder(); var result = await Cli.Wrap("echo") .WithArguments(["hello"]) .WithStandardOutputPipe(PipeTarget.ToStringBuilder(output)) .WithStandardErrorPipe(PipeTarget.ToStringBuilder(error)) .ExecuteAsync(); Console.WriteLine(output.ToString()); ``` ```csharp var result = await Cli.Wrap("echo") .WithArguments(["hello"]) .ExecuteBufferedAsync(); Console.WriteLine(result.StandardOutput); ``` -------------------------------- ### Execute Command with Method Chaining Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Demonstrates fluent configuration of a command including arguments, environment variables, and validation, followed by buffered execution. ```csharp var result = await Cli.Wrap("dotnet") .WithArguments(args => args .Add("build") .Add("-c") .Add("Release") ) .WithWorkingDirectory("/path/to/project") .WithEnvironmentVariables(env => env .Set("BUILD_NUMBER", "42") .Set("COMPILER", "clang") ) .WithValidation(CommandResultValidation.ZeroExitCode) .ExecuteBufferedAsync(); if (result.IsSuccess) Console.WriteLine("Build succeeded"); else Console.WriteLine($"Build failed: {result.StandardError}"); ``` -------------------------------- ### Create a command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Initializes a new command instance targeting the specified executable path. ```csharp var cmd = Cli.Wrap("path/to/executable"); ``` -------------------------------- ### LoadUserProfile method for CredentialsBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Determines whether the user profile should be loaded when the process starts. ```csharp public CredentialsBuilder LoadUserProfile(bool loadUserProfile = true) ``` -------------------------------- ### Build() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Finalizes the configuration and returns the environment variables. ```APIDOC ## Build() ### Description Builds the resulting environment variables. ### Returns - **IReadOnlyDictionary** - A read-only dictionary of environment variables. ``` -------------------------------- ### Cli.Wrap(string) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Initializes a new command targeting the specified executable path. ```APIDOC ## Cli.Wrap(string) ### Description Creates a new command instance for the specified executable. ### Signature `Command Cli.Wrap(string targetFilePath)` ``` -------------------------------- ### Setting Command Arguments Source: https://github.com/tyrrrz/cliwrap/wiki/Migration-guide-(from-v2.5-to-v3.0) Demonstrates how to set command arguments using strings or arrays in v2.5 and v3.0, including the new builder pattern. ```csharp Cli.Wrap("foo").SetArguments("bar baz"); ``` ```csharp Cli.Wrap("foo").SetArguments(new[] {"bar", "baz"}); ``` ```csharp Cli.Wrap("foo").WithArguments("bar baz"); ``` ```csharp Cli.Wrap("foo").WithArguments(new[] {"bar", "baz"}); ``` ```csharp Cli.Wrap("foo").WithArguments(a => a.Add("bar").Add("baz")); ``` -------------------------------- ### Handle command output via callbacks Source: https://github.com/tyrrrz/cliwrap/wiki/Migration-guide-(from-v2.5-to-v3.0) Demonstrates the legacy approach for handling output streams using callbacks. ```csharp var result = await Cli.Wrap("cli.exe") .SetStandardOutputCallback(l => Console.WriteLine($"StdOut> {l}")) .SetStandardErrorCallback(l => Console.WriteLine($"StdErr> {l}")) .ExecuteAsync(); ``` -------------------------------- ### InvalidOperationException Error Message Source: https://github.com/tyrrrz/cliwrap/wiki/Troubleshooting The specific exception message thrown when .NET fails to start a process. ```text InvalidOperationException: Failed to obtain the handle when starting a process. This could mean that the target executable doesn't exist or that execute permission is missing. ``` -------------------------------- ### Initialize Credentials Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Constructor for defining user credentials for process execution. ```csharp public Credentials( string? domain = null, string? userName = null, string? password = null, bool loadUserProfile = false ) ``` -------------------------------- ### Configuration Methods Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Fluent methods for configuring the Command instance. Each method returns a new immutable instance of the Command. ```APIDOC ## Configuration Methods ### Methods - **WithTargetFile(string targetFilePath)**: Sets the path to the executable. - **WithArguments(string arguments)**: Sets the command-line arguments. - **WithWorkingDirectory(string workingDirPath)**: Sets the working directory. - **WithResourcePolicy(ResourcePolicy resourcePolicy)**: Sets the resource policy. - **WithCredentials(Credentials credentials)**: Sets the user credentials. - **WithEnvironmentVariables(IReadOnlyDictionary environmentVariables)**: Sets environment variables. - **WithValidation(CommandResultValidation validation)**: Sets the validation strategy. - **WithStandardInputPipe(PipeSource standardInputPipe)**: Sets the standard input pipe. - **WithStandardOutputPipe(PipeTarget standardOutputPipe)**: Sets the standard output pipe. - **WithStandardErrorPipe(PipeTarget standardErrorPipe)**: Sets the standard error pipe. ``` -------------------------------- ### Build() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Builds the resulting credentials. ```APIDOC ## Build() ### Description Builds the resulting credentials. ### Returns - **Credentials** - A new credentials instance. ``` -------------------------------- ### Configure Pipes with Configuration Methods Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Uses WithStandardInputPipe and WithStandardOutputPipe to redirect streams using file streams. ```csharp await using var input = File.OpenRead("data.csv"); await using var output = File.Create("sorted.csv"); await Cli.Wrap("sort") .WithStandardInputPipe(PipeSource.FromStream(input)) .WithStandardOutputPipe(PipeTarget.ToStream(output)) .ExecuteAsync(); ``` -------------------------------- ### Combine event streams with file piping Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Demonstrates how to pipe command output to a file while simultaneously iterating over the command events. ```csharp var cmd = Cli.Wrap("dotnet").WithArguments(["test"]) | PipeTarget.ToFile("test-output.log"); // Iterate as an event stream and pipe to a file at the same time // (execution models preserve configured pipes) await foreach (var cmdEvent in cmd.ListenAsync()) { // ... } ``` -------------------------------- ### Execute and get result Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Executes the command and retrieves the result containing exit code, success status, and duration. ```csharp var result = await cmd.ExecuteAsync(); Console.WriteLine($"Exit code: {result.ExitCode}"); Console.WriteLine($"Success: {result.IsSuccess}"); Console.WriteLine($"Duration: {result.RunTime}"); ``` -------------------------------- ### Build() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Builds the resulting resource policy. ```APIDOC ## Build() ### Description Builds the resulting resource policy. ### Returns - **ResourcePolicy** - A new resource policy instance. ``` -------------------------------- ### Create a new command with Cli.Wrap Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Initializes a command targeting a specific executable. Requires the CliWrap namespace. ```csharp using CliWrap; var cmd = Cli.Wrap("git"); ``` -------------------------------- ### Immutable Command Configuration Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/INDEX.md Demonstrates how configuration methods return new command instances, leaving the original command unchanged. ```csharp var cmd = Cli.Wrap("git"); var cmd2 = cmd.WithArguments(["--version"]); // cmd unchanged, cmd2 has arguments ``` -------------------------------- ### Configure user credentials with CredentialsBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Provides a fluent API to set domain, username, password, and user profile loading for command execution. ```csharp public class CredentialsBuilder { public CredentialsBuilder SetDomain(string? domain); public CredentialsBuilder SetUserName(string? userName); public CredentialsBuilder SetPassword(string? password); public CredentialsBuilder LoadUserProfile(bool loadUserProfile = true); public Credentials Build(); } ``` -------------------------------- ### Command Configuration Methods Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Fluent methods used to configure command execution parameters such as arguments, working directory, and environment variables. ```APIDOC ## Configuration Methods - **WithTargetFile(string)**: Changes the executable. - **WithArguments(string/IEnumerable/Action)**: Sets command arguments using manual strings, arrays, or a builder. - **WithWorkingDirectory(string)**: Sets the working directory for the process. - **WithEnvironmentVariables(...)**: Sets environment variables for the process. - **WithCredentials(...)**: Sets user credentials for the process. - **WithResourcePolicy(...)**: Sets process priority and affinity. - **WithValidation(...)**: Configures the validation strategy for the exit code. - **WithStandardInputPipe(PipeSource)**: Configures the source for standard input. - **WithStandardOutputPipe(PipeTarget)**: Configures the target for standard output. - **WithStandardErrorPipe(PipeTarget)**: Configures the target for standard error. ``` -------------------------------- ### Basic Command Execution Comparison Source: https://github.com/tyrrrz/cliwrap/wiki/Migration-guide-(from-v2.5-to-v3.0) Compares basic command execution and result retrieval between v2.5 and v3.0. ```csharp var result = await Cli.Wrap("cli.exe") .SetArguments("Hello world!") .ExecuteAsync(); var exitCode = result.ExitCode; var stdOut = result.StandardOutput; var stdErr = result.StandardError; var startTime = result.StartTime; var exitTime = result.ExitTime; var runTime = result.RunTime; ``` ```csharp var result = await Cli.Wrap("cli.exe") .WithArguments("Hello world!") .ExecuteBufferedAsync(); var exitCode = result.ExitCode; var stdOut = result.StandardOutput; var stdErr = result.StandardError; var startTime = result.StartTime; var exitTime = result.ExitTime; var runTime = result.RunTime; ``` -------------------------------- ### Handle unsupported credentials exception in C# Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/errors.md Demonstrates catching NotSupportedException when applying credentials on incompatible platforms. ```csharp try { await Cli.Wrap("echo") .WithCredentials(creds => creds .SetDomain("CORP") .SetUserName("user") .SetPassword("pass") .LoadUserProfile() ) .ExecuteAsync(); } catch (NotSupportedException ex) { Console.WriteLine("Credentials not supported: " + ex.Message); } ``` -------------------------------- ### Initialize ResourcePolicy Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Constructor for defining process resource constraints. ```csharp public ResourcePolicy( ProcessPriorityClass? priority = null, nint? affinity = null, nint? minWorkingSet = null, nint? maxWorkingSet = null ) ``` -------------------------------- ### Observe command events as a push-based stream Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Uses Rx.NET to observe command events as they occur. The stream is cold and provides no back pressure. ```csharp using System.Reactive; using CliWrap; using CliWrap.EventStream; var cmd = Cli.Wrap("dotnet").WithArguments(["build"]); await cmd.Observe().ForEachAsync(cmdEvent => { switch (cmdEvent) { case StartedCommandEvent started: _output.WriteLine($"Process started; ID: {started.ProcessId}"); break; case StandardOutputCommandEvent stdOut: _output.WriteLine($"Out> {stdOut.Text}"); break; case StandardErrorCommandEvent stdErr: _output.WriteLine($"Err> {stdErr.Text}"); break; case ExitedCommandEvent exited: _output.WriteLine($"Process exited; Code: {exited.ExitCode}"); break; } }); ``` -------------------------------- ### Command.WithTargetFile() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a copy of an existing command with an updated target file path. ```APIDOC ## Command.WithTargetFile(string targetFilePath) ### Description Creates a copy of this command with the target file path set to the specified value. ### Parameters #### Path Parameters - **targetFilePath** (string) - Required - New target file path ### Returns - **Command** - A new command instance with the updated target file path. ``` -------------------------------- ### Command configuration methods Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Common methods used to configure command execution behavior. ```csharp .WithTargetFile("python") ``` ```csharp .WithArguments("-l -a") ``` ```csharp .WithArguments(["ls", "-la"]) ``` ```csharp .WithArguments(a => a.Add("commit").Add("-m").Add("msg")) ``` ```csharp .WithWorkingDirectory("/tmp") ``` ```csharp .WithEnvironmentVariables(dict) ``` ```csharp .WithCredentials(c => c.SetUserName("user")) ``` ```csharp .WithResourcePolicy(p => p.SetPriority(High)) ``` ```csharp .WithValidation(CommandResultValidation.None) ``` ```csharp .WithStandardInputPipe(PipeSource.FromFile("in")) ``` ```csharp .WithStandardOutputPipe(PipeTarget.ToFile("out")) ``` ```csharp .WithStandardErrorPipe(PipeTarget.ToFile("err")) ``` -------------------------------- ### WithCredentials() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Configures user credentials for the command. ```APIDOC ## WithCredentials(Credentials credentials) ### Description Creates a copy of this command with the user credentials set to the specified value. ### Parameters - **credentials** (Credentials) - Required - User credentials configuration ### Returns - **Command** - A new command instance with the updated credentials. ## WithCredentials(Action configure) ### Description Creates a copy of this command with the user credentials configured via the specified delegate. ### Parameters - **configure** (Action) - Required - Delegate to configure the credentials builder ### Returns - **Command** - A new command instance with the configured credentials. ``` -------------------------------- ### Execute a basic command Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Configures and runs a command asynchronously, returning a CommandResult containing exit information. ```csharp using CliWrap; var result = await Cli.Wrap("path/to/exe") .WithArguments(["--foo", "bar"]) .WithWorkingDirectory("work/dir/path") .ExecuteAsync(); // Result contains: // -- result.ExitCode (int) // -- result.IsSuccess (bool) // -- result.StartTime (DateTimeOffset) // -- result.ExitTime (DateTimeOffset) // -- result.RunTime (TimeSpan) ``` -------------------------------- ### Pipe complex command chains Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Demonstrates chaining strings, commands, and multiple output targets in a single pipeline. ```csharp var cmd = """ { "name": "Alice", "age": 30 } """ | Cli.Wrap("jq").WithArguments([".name"]) | Cli.Wrap("tee").WithArguments(["formatted.json"]) | (Console.WriteLine, Console.Error.WriteLine); await cmd.ExecuteAsync(); ``` -------------------------------- ### Handle unsupported resource policy exception in C# Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/errors.md Demonstrates catching NotSupportedException when applying resource policies on incompatible platforms. ```csharp try { await Cli.Wrap("echo") .WithResourcePolicy(policy => policy .SetPriority(ProcessPriorityClass.High) .SetAffinity(0b1100) // Cores 2 and 3 .SetMinWorkingSet(new IntPtr(10000000)) .SetMaxWorkingSet(new IntPtr(100000000)) ) .ExecuteAsync(); } catch (NotSupportedException ex) { Console.WriteLine("Resource policy not supported: " + ex.Message); } ``` -------------------------------- ### WithEnvironmentVariables(Action) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a copy of the command with environment variables configured via a delegate. ```APIDOC ## WithEnvironmentVariables(Action) ### Description Creates a copy of this command with the environment variables configured via the specified delegate. ### Parameters - **configure** (Action) - Required - Delegate to configure the environment variables builder ### Returns - **Command** - A new command instance with the configured environment variables. ``` -------------------------------- ### Cli.Wrap() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a new command instance targeting a specific executable, batch file, or script. ```APIDOC ## Cli.Wrap(string targetFilePath) ### Description Creates a new command that targets the specified command-line executable, batch file, or script. ### Parameters #### Path Parameters - **targetFilePath** (string) - Required - Path to the executable, batch file, or script to run ### Returns - **Command** - A new command instance configured with the target executable path. ``` -------------------------------- ### Process output in real-time Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Uses a delegate to handle output lines as they are produced by the command. ```csharp await Cli.Wrap("find") .WithArguments(["/usr/bin"]) .WithStandardOutputPipe(PipeTarget.ToDelegate(line => Console.WriteLine($"Found: {line}") )) .ExecuteAsync(); ``` -------------------------------- ### ListenAsync Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Executes a command and streams events as they occur. ```APIDOC ## ListenAsync ### Description Executes the command and returns an IAsyncEnumerable of command events. ### Method Async Stream ### Events - **StartedCommandEvent** - Emitted when the process starts. - **StandardOutputCommandEvent** - Emitted when text is written to stdout. - **StandardErrorCommandEvent** - Emitted when text is written to stderr. - **ExitedCommandEvent** - Emitted when the process exits. ``` -------------------------------- ### Execute commands with different models Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Choose between standard, buffered, or event-stream execution based on whether you need output capture or real-time event processing. ```csharp var result = await cmd.ExecuteAsync(); // Returns: CommandResult { ExitCode, IsSuccess, StartTime, ExitTime, RunTime } ``` ```csharp var result = await cmd.ExecuteBufferedAsync(); // Returns: BufferedCommandResult { ..CommandResult, StandardOutput, StandardError } ``` ```csharp await foreach (var evt in cmd.ListenAsync()) { // StartedCommandEvent { ProcessId } // StandardOutputCommandEvent { Text } // StandardErrorCommandEvent { Text } // ExitedCommandEvent { ExitCode } } ``` -------------------------------- ### Execute with output buffering Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Executes the command and captures standard output and error streams into memory. ```csharp var result = await cmd.ExecuteBufferedAsync(); Console.WriteLine(result.StandardOutput); Console.WriteLine(result.StandardError); ``` -------------------------------- ### Configure Pipe Sources Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Methods to define the input source for a command. ```csharp .WithStandardInputPipe(PipeSource.Null) ``` ```csharp PipeSource.FromFile("input.txt") ``` ```csharp PipeSource.FromStream(fileStream) ``` ```csharp PipeSource.FromString("data") ``` ```csharp PipeSource.FromBytes(data) ``` ```csharp PipeSource.FromCommand(cmd1) ``` ```csharp PipeSource.Create(s => s.Write(...)) ``` -------------------------------- ### Command.ExecuteAsync() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Executes the configured command asynchronously. ```APIDOC ## ExecuteAsync() ### Description Executes the command as defined by the current configuration and returns the result. ### Signature `public Task ExecuteAsync(CancellationToken cancellationToken = default)` ``` -------------------------------- ### Capture simple output with CliWrap Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/buffered-execution.md Captures standard output from a command using ExecuteBufferedAsync. ```csharp using CliWrap; using CliWrap.Buffered; var result = await Cli.Wrap("echo") .WithArguments(["Hello, World!"]) .ExecuteBufferedAsync(); Console.WriteLine(result.StandardOutput); // Output: Hello, World! ``` -------------------------------- ### Pipe Standard Input Source: https://github.com/tyrrrz/cliwrap/wiki/Migration-guide-(from-v2.5-to-v3.0) Demonstrates the new piping API in v3.0 compared to the legacy SetStandardInput method. ```csharp var result = await Cli.Wrap("cli.exe") .SetStandardInput("Hello world from stdin!") .ExecuteAsync(); ``` ```csharp var result = await Cli.Wrap("cli.exe") .WithStandardInputPipe(PipeSource.FromString("Hello world from stdin!")) .ExecuteAsync(); ``` ```csharp var result = await ("Hello world from stdin!" | Cli.Wrap("cli.exe")).ExecuteAsync(); ``` -------------------------------- ### Pipe from String to Command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Pipes input from a string directly into a command. ```csharp var cmd = "hello\nworld" | Cli.Wrap("cat"); ``` -------------------------------- ### Command Execution Methods Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Methods for executing configured commands, including standard execution, buffered output, and event streaming. ```APIDOC ## Command Execution ### ExecuteAsync() Executes the command and returns a `CommandResult` containing the exit code, success status, and duration. ### ExecuteBufferedAsync() Executes the command and captures the standard output and standard error streams into the result. ### ListenAsync() Executes the command and returns an `IAsyncEnumerable` of `CommandEvent` objects, allowing for real-time processing of output streams. ``` -------------------------------- ### Set command-line arguments in CliWrap Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Configure arguments using arrays, builders, or raw strings. Prefer builders over raw strings to avoid manual escaping and security risks. ```csharp var cmd = Cli.Wrap("git") // Each element is formatted as a separate argument. // Equivalent to: `git commit -m "my commit"` .WithArguments(["commit", "-m", "my commit"]); ``` ```csharp var cmd = Cli.Wrap("git") // Each Add(...) call takes care of formatting automatically. // Equivalent to: `git clone https://github.com/Tyrrrz/CliWrap --depth 20` .WithArguments(args => args .Add("clone") .Add("https://github.com/Tyrrrz/CliWrap") .Add("--depth") .Add(20) ); ``` ```csharp var forcePush = true; var cmd = Cli.Wrap("git") // Arguments can also be constructed in an imperative fashion. // Equivalent to: `git push --force` .WithArguments(args => { args.Add("push"); if (forcePush) args.Add("--force"); }); ``` ```csharp var cmd = Cli.Wrap("git") // Avoid using this overload unless you really have to. // Equivalent to: `git commit -m "my commit"` .WithArguments("commit -m \"my commit\""); ``` -------------------------------- ### operator |(Command, Action) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Pipes command output line-by-line to a sync delegate. ```APIDOC ## operator |(Command, Action) ### Description Pipes command output line-by-line to a sync delegate. ### Signature `public static Command operator |(Command source, Action target)` ### Example ```csharp var lines = new List(); var cmd = Cli.Wrap("ls") | (line => lines.Add(line)); ``` ``` -------------------------------- ### Build arguments string Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Generates the final command-line argument string from the builder instance. ```csharp public string Build() ``` ```csharp var args = new ArgumentsBuilder() .Add("commit") .Add("-m") .Add("my commit") .Build(); // Result: "commit -m \"my commit\"" ``` -------------------------------- ### WithEnvironmentVariables(IReadOnlyDictionary) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a copy of the command with environment variables set to the specified dictionary values. Setting a value to null removes the variable. ```APIDOC ## WithEnvironmentVariables(IReadOnlyDictionary) ### Description Creates a copy of this command with the environment variables set to the specified value. Set a variable value to null to remove it. ### Parameters - **environmentVariables** (IReadOnlyDictionary) - Required - Dictionary of environment variables ### Returns - **Command** - A new command instance with the updated environment variables. ``` -------------------------------- ### Configure Environment Variables with Dictionary Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Sets environment variables using a dictionary. Passing null as a value removes the corresponding variable. ```csharp public Command WithEnvironmentVariables(IReadOnlyDictionary environmentVariables) ``` ```csharp var cmd = Cli.Wrap("npm") .WithEnvironmentVariables(new Dictionary { { "NODE_ENV", "production" }, { "DEBUG", null } // Remove DEBUG variable }) .WithArguments(["build"]); ``` -------------------------------- ### WithArguments Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Sets the command-line arguments passed to the child process. Supports arrays, builders, or raw strings. ```APIDOC ## WithArguments(args) ### Description Sets the command-line arguments passed to the child process. It is recommended to use the array or builder overloads to ensure proper escaping. ### Parameters - **args** (IEnumerable | Action | string) - Required - The arguments to pass to the process. ``` -------------------------------- ### Pipe from Byte Array to Command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Pipes input from a byte array into a command. ```csharp var data = new byte[] { 0x48, 0x69 }; // "Hi" var cmd = data | Cli.Wrap("cat"); ``` -------------------------------- ### ListenAsync(CancellationToken cancellationToken) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Executes the command as a pull-based event stream using the default encoding for both standard output and standard error. ```APIDOC ## ListenAsync(CancellationToken cancellationToken) ### Description Executes the command as a pull-based event stream. Uses Encoding.Default for both standard output and standard error. ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token for cancellation ### Returns - **IAsyncEnumerable** - An async enumerable yielding command events. ### Example ```csharp await foreach (var cmdEvent in Cli.Wrap("ls").ListenAsync()) { switch (cmdEvent) { case StandardOutputCommandEvent stdOut: Console.WriteLine(stdOut.Text); break; } } ``` ``` -------------------------------- ### WithWorkingDirectory Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Sets the working directory for the child process. ```APIDOC ## WithWorkingDirectory(path) ### Description Sets the working directory of the child process. Defaults to the current working directory. ### Parameters - **path** (string) - Required - The directory path. ``` -------------------------------- ### Build method for CredentialsBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Finalizes the configuration and returns a new Credentials instance. ```csharp public Credentials Build() ``` -------------------------------- ### ListenAsync(Encoding, Encoding, CancellationToken, CancellationToken) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Executes a command as a pull-based event stream with separate encodings and distinct tokens for forceful and graceful cancellation. ```APIDOC ## ListenAsync(Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken forcefulCancellationToken, CancellationToken gracefulCancellationToken) ### Description Executes the command as a pull-based event stream. Yields CommandEvent instances as they occur. ### Parameters - **standardOutputEncoding** (Encoding) - Required - Encoding to use for decoding stdout lines - **standardErrorEncoding** (Encoding) - Required - Encoding to use for decoding stderr lines - **forcefulCancellationToken** (CancellationToken) - Required - Token for forcefully terminating the process - **gracefulCancellationToken** (CancellationToken) - Required - Token for gracefully terminating the process ### Returns - **IAsyncEnumerable** - An async enumerable yielding command events (StartedCommandEvent, StandardOutputCommandEvent, StandardErrorCommandEvent, ExitedCommandEvent). ### Example ```csharp await foreach (var cmdEvent in Cli.Wrap("git") .WithArguments(["log", "--oneline"]) .ListenAsync(Encoding.UTF8, Encoding.UTF8, CancellationToken.None, CancellationToken.None)) { switch (cmdEvent) { case StartedCommandEvent started: Console.WriteLine($"Process {started.ProcessId} started"); break; case StandardOutputCommandEvent stdOut: Console.WriteLine($" {stdOut.Text}"); break; case StandardErrorCommandEvent stdErr: Console.WriteLine($"Error: {stdErr.Text}"); break; case ExitedCommandEvent exited: Console.WriteLine($"Process exited with code {exited.ExitCode}"); break; } } ``` ``` -------------------------------- ### Configure command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Configures command parameters including arguments, working directory, environment variables, and validation rules. ```csharp var cmd = Cli.Wrap("git") .WithArguments(["commit", "-m", "message"]) .WithWorkingDirectory("/path/to/repo") .WithEnvironmentVariables(new Dictionary { { "GIT_AUTHOR", "name" } }) .WithValidation(CommandResultValidation.ZeroExitCode); ``` -------------------------------- ### Input Piping Shorthand Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Shorthand syntax for piping sources into command input. ```csharp var cmd = PipeSource.FromFile("input.txt") | Cli.Wrap("cat"); ``` ```csharp var cmd = "data" | Cli.Wrap("cat"); ``` ```csharp var cmd = new byte[] { ... } | Cli.Wrap("cat"); ``` ```csharp using var file = File.OpenRead("in.txt"); var cmd = file | Cli.Wrap("cat"); ``` -------------------------------- ### ListenAsync(Encoding encoding, CancellationToken cancellationToken) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Executes the command as a pull-based event stream using a specified encoding for both standard output and standard error. ```APIDOC ## ListenAsync(Encoding encoding, CancellationToken cancellationToken) ### Description Executes the command as a pull-based event stream. Uses the same encoding for both standard output and standard error. ### Parameters - **encoding** (Encoding) - Required - Encoding to use for decoding both stdout and stderr lines - **cancellationToken** (CancellationToken) - Optional - Cancellation token for cancellation ### Returns - **IAsyncEnumerable** - An async enumerable yielding command events. ``` -------------------------------- ### Pipe from Stream to Command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Pipes input from an open stream into a command. ```csharp using var file = File.OpenRead("input.txt"); var cmd = file | Cli.Wrap("grep").WithArguments(["pattern"]); ``` -------------------------------- ### Setting Working Directory Source: https://github.com/tyrrrz/cliwrap/wiki/Migration-guide-(from-v2.5-to-v3.0) Updates the working directory configuration method. ```csharp Cli.Wrap("foo").SetWorkingDirectory("path") ``` ```csharp Cli.Wrap("foo").WithWorkingDirectory("path") ``` -------------------------------- ### Build environment variables Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Finalizes the configuration and returns the resulting environment variables as a read-only dictionary. ```csharp public IReadOnlyDictionary Build() ``` -------------------------------- ### Comprehensive error handling in C# Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/errors.md Demonstrates catching specific CliWrap exceptions like CommandExecutionException, OperationCanceledException, and TimeoutException. ```csharp using CliWrap; using CliWrap.Exceptions; try { var result = await Cli.Wrap("git") .WithArguments(["clone", "https://github.com/example/repo.git"]) .ExecuteAsync(); Console.WriteLine($"Success: exit code {result.ExitCode}"); } catch (CommandExecutionException ex) { Console.WriteLine($"Command execution failed: {ex.Message}"); Console.WriteLine($"Exit code: {ex.ExitCode}"); Console.WriteLine($"Command: {ex.Command.TargetFilePath} {ex.Command.Arguments}"); } catch (OperationCanceledException ex) { Console.WriteLine($"Command was canceled: {ex.Message}"); } catch (TimeoutException ex) { Console.WriteLine($"Command timeout: {ex.Message}"); } catch (NotSupportedException ex) { Console.WriteLine($"Operation not supported: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.GetType().Name}: {ex.Message}"); } ``` -------------------------------- ### Basic Command Execution Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Standard usage of ExecuteAsync to run a command and access the result. ```csharp using CliWrap; var result = await Cli.Wrap("git") .WithArguments(["--version"]) .ExecuteAsync(); Console.WriteLine($"Exit code: {result.ExitCode}"); Console.WriteLine($"Success: {result.IsSuccess}"); ``` -------------------------------- ### Create PipeSource from Command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Pipes the standard output of one command into another. ```csharp public static PipeSource FromCommand(Command command) public static PipeSource FromCommand( Command command, Func copyStreamAsync ) ``` ```csharp var cmd1 = Cli.Wrap("cat").WithArguments(["input.txt"]); var cmd2 = PipeSource.FromCommand(cmd1) | Cli.Wrap("grep").WithArguments(["pattern"]); ``` -------------------------------- ### Use ArgumentsBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Provides a fluent API for constructing and escaping command-line argument strings. ```csharp public partial class ArgumentsBuilder { public ArgumentsBuilder Add(string value, bool escape); public ArgumentsBuilder Add(IEnumerable values, bool escape); public ArgumentsBuilder Add(IFormattable value, IFormatProvider formatProvider, bool escape = true); public ArgumentsBuilder Add(IEnumerable values, IFormatProvider formatProvider, bool escape = true); public string Build(); public static string Escape(string argument); } ``` -------------------------------- ### Configure Environment Variables with Delegate Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Configures environment variables using an EnvironmentVariablesBuilder delegate. ```csharp public Command WithEnvironmentVariables(Action configure) ``` -------------------------------- ### Configure resource policy with ResourcePolicyBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/types.md Provides a fluent API to set process priority, CPU affinity, and working set limits for command execution. ```csharp public class ResourcePolicyBuilder { public ResourcePolicyBuilder SetPriority(ProcessPriorityClass? priority); public ResourcePolicyBuilder SetAffinity(nint? affinity); public ResourcePolicyBuilder SetMinWorkingSet(nint? minWorkingSet); public ResourcePolicyBuilder SetMaxWorkingSet(nint? maxWorkingSet); public ResourcePolicy Build(); } ``` -------------------------------- ### ListenAsync(Encoding, Encoding, CancellationToken) Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Executes a command as a pull-based event stream with separate encodings and a single cancellation token. ```APIDOC ## ListenAsync(Encoding standardOutputEncoding, Encoding standardErrorEncoding, CancellationToken cancellationToken) ### Description Executes the command as a pull-based event stream. Separate encodings for stdout and stderr, single cancellation token for both graceful and forceful cancellation. ### Parameters - **standardOutputEncoding** (Encoding) - Required - Encoding to use for decoding stdout lines - **standardErrorEncoding** (Encoding) - Required - Encoding to use for decoding stderr lines - **cancellationToken** (CancellationToken) - Optional - Cancellation token for cancellation ### Returns - **IAsyncEnumerable** - An async enumerable yielding command events. ### Example ```csharp await foreach (var cmdEvent in Cli.Wrap("python") .WithArguments(["-c", "print('hello')"]) .ListenAsync(Encoding.UTF8, Encoding.UTF8)) { if (cmdEvent is StandardOutputCommandEvent stdOut) { Console.WriteLine($"Output: {stdOut.Text}"); } } ``` ``` -------------------------------- ### Set multiple environment variables from enumerable Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Configures multiple environment variables using a sequence of key-value pairs. ```csharp public EnvironmentVariablesBuilder Set(IEnumerable> variables) ``` -------------------------------- ### ListenAsync Overloads for Event Streaming Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Methods for executing commands as pull-based event streams. Use the overload with an Encoding parameter for specific output decoding or the default overload for standard behavior. ```csharp public async IAsyncEnumerable ListenAsync( this Command command, Encoding encoding, [EnumeratorCancellation] CancellationToken cancellationToken = default ) ``` ```csharp public async IAsyncEnumerable ListenAsync( this Command command, [EnumeratorCancellation] CancellationToken cancellationToken = default ) ``` -------------------------------- ### Create Custom PipeSource Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a pipe source using a custom delegate for handling the stream. ```csharp public static PipeSource Create(Func handlePipeAsync) public static PipeSource Create(Action handlePipe) ``` ```csharp var source = PipeSource.Create(async (destination, ct) => { await destination.WriteAsync(Encoding.Default.GetBytes("input data"), ct); }); ``` -------------------------------- ### Pipe stdout into a file and stderr into a StringBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Splits output streams into different targets simultaneously. ```csharp var errorBuffer = new StringBuilder(); var cmd = Cli.Wrap("curl").WithArguments(["-s", "https://api.example.com/data"]) | ( PipeTarget.ToFile("response.json"), PipeTarget.ToStringBuilder(errorBuffer) ); await cmd.ExecuteAsync(); ``` -------------------------------- ### Configure command target file Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a new immutable command instance with an updated target executable path. ```csharp var cmd = Cli.Wrap("git").WithTargetFile("svn"); ``` -------------------------------- ### CommandTask Methods Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Methods for awaiting, configuring, and disposing of command tasks. ```csharp public TaskAwaiter GetAwaiter() ``` ```csharp public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) ``` ```csharp public void Dispose() ``` -------------------------------- ### Set multiple environment variables from dictionary Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Configures multiple environment variables using a read-only dictionary. ```csharp public EnvironmentVariablesBuilder Set(IReadOnlyDictionary variables) ``` -------------------------------- ### Default Credentials Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Static field providing empty credentials. ```csharp public static Credentials Default { get; } ``` -------------------------------- ### Output Piping Shorthand Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/quick-reference.md Shorthand syntax for redirecting command output to various targets. ```csharp var cmd = Cli.Wrap("echo") .WithArguments(["hello"]) | PipeTarget.ToFile("output.txt"); ``` ```csharp var cmd = Cli.Wrap("date") | File.Create("out.txt"); ``` ```csharp var sb = new StringBuilder(); var cmd = Cli.Wrap("whoami") | sb; ``` ```csharp var cmd = Cli.Wrap("cat") .WithArguments(["file.log"]) | (line => Console.WriteLine(line)); // Line-by-line ``` -------------------------------- ### Configure standard stream pipes Source: https://github.com/tyrrrz/cliwrap/blob/prime/Readme.md Routes standard output and error streams to StringBuilder buffers for in-memory inspection. ```csharp using CliWrap; var stdOutBuffer = new StringBuilder(); var stdErrBuffer = new StringBuilder(); var result = await Cli.Wrap("path/to/exe") .WithArguments(["--foo", "bar"]) .WithWorkingDirectory("work/dir/path") // This can be simplified with `ExecuteBufferedAsync()` .WithStandardOutputPipe(PipeTarget.ToStringBuilder(stdOutBuffer)) .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer)) .ExecuteAsync(); // Access stdout & stderr buffered in-memory as strings var stdOut = stdOutBuffer.ToString(); var stdErr = stdErrBuffer.ToString(); ``` -------------------------------- ### Capture output to StringBuilder Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Capture command output as text by piping it into a StringBuilder instance. ```csharp var output = new StringBuilder(); await Cli.Wrap("git") .WithArguments(["log", "--oneline", "-n", "1"]) .WithStandardOutputPipe(PipeTarget.ToStringBuilder(output)) .ExecuteAsync(); Console.WriteLine(output.ToString()); ``` -------------------------------- ### Command.WithArguments() Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/api-reference.md Creates a copy of an existing command with updated arguments. ```APIDOC ## Command.WithArguments(string arguments) ### Description Creates a copy of this command with the arguments set to the specified string. Note that this overload does not perform automatic escaping. ### Parameters #### Path Parameters - **arguments** (string) - Required - Raw arguments string (no automatic escaping) ### Returns - **Command** - A new command instance with the updated arguments. ``` -------------------------------- ### Monitor real-time progress Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/event-stream-execution.md Parses standard output in real-time to track specific progress indicators. ```csharp var completedCount = 0; await foreach (var cmdEvent in Cli.Wrap("npm") .WithArguments(["install"]) .ListenAsync()) { if (cmdEvent is StandardOutputCommandEvent stdOut) { if (stdOut.Text.Contains("added")) { completedCount++; Console.Write("."); if (completedCount % 50 == 0) Console.WriteLine(); } else { Console.WriteLine(stdOut.Text); } } if (cmdEvent is ExitedCommandEvent exited) { Console.WriteLine($"\nDone. Exit code: {exited.ExitCode}"); } } ``` -------------------------------- ### Pipe from FileSource to Command Source: https://github.com/tyrrrz/cliwrap/blob/prime/_autodocs/guide-piping.md Pipes input from a file into a command using PipeSource. ```csharp var source = PipeSource.FromFile("input.txt"); var cmd = source | Cli.Wrap("cat"); ```