{"id":15038106,"url":"https://github.com/tyrrrz/clifx","last_synced_at":"2025-05-13T17:04:46.992Z","repository":{"id":40693909,"uuid":"189863985","full_name":"Tyrrrz/CliFx","owner":"Tyrrrz","description":"Class-first framework for building command-line interfaces","archived":false,"fork":false,"pushed_at":"2025-05-12T19:53:11.000Z","size":1305,"stargazers_count":1552,"open_issues_count":4,"forks_count":63,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-05-12T20:52:04.740Z","etag":null,"topics":["cli","command","command-line","dotnet","dotnet-core","dotnet-standard","framework","terminal"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Tyrrrz.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":"License.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"Tyrrrz","patreon":"Tyrrrz","custom":["tyrrrz.me/donate"]}},"created_at":"2019-06-02T15:34:41.000Z","updated_at":"2025-05-12T20:03:10.000Z","dependencies_parsed_at":"2023-12-25T18:03:44.401Z","dependency_job_id":"7e0c3983-46aa-464a-ba9b-8d7e1fbf4ded","html_url":"https://github.com/Tyrrrz/CliFx","commit_stats":{"total_commits":424,"total_committers":22,"mean_commits":"19.272727272727273","dds":0.6981132075471699,"last_synced_commit":"eff84fd7aebb4b381ad4674ffd7184471636ecd4"},"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tyrrrz%2FCliFx","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tyrrrz%2FCliFx/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tyrrrz%2FCliFx/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tyrrrz%2FCliFx/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Tyrrrz","download_url":"https://codeload.github.com/Tyrrrz/CliFx/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253990459,"owners_count":21995773,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","command","command-line","dotnet","dotnet-core","dotnet-standard","framework","terminal"],"created_at":"2024-09-24T20:37:07.543Z","updated_at":"2025-05-13T17:04:46.956Z","avatar_url":"https://github.com/Tyrrrz.png","language":"C#","funding_links":["https://github.com/sponsors/Tyrrrz","https://patreon.com/Tyrrrz","tyrrrz.me/donate"],"categories":[],"sub_categories":[],"readme":"# CliFx\n\n[![Status](https://img.shields.io/badge/status-maintenance-ffd700.svg)](https://github.com/Tyrrrz/.github/blob/master/docs/project-status.md)\n[![Made in Ukraine](https://img.shields.io/badge/made_in-ukraine-ffd700.svg?labelColor=0057b7)](https://tyrrrz.me/ukraine)\n[![Build](https://img.shields.io/github/actions/workflow/status/Tyrrrz/CliFx/main.yml?branch=master)](https://github.com/Tyrrrz/CliFx/actions)\n[![Coverage](https://img.shields.io/codecov/c/github/Tyrrrz/CliFx/master)](https://codecov.io/gh/Tyrrrz/CliFx)\n[![Version](https://img.shields.io/nuget/v/CliFx.svg)](https://nuget.org/packages/CliFx)\n[![Downloads](https://img.shields.io/nuget/dt/CliFx.svg)](https://nuget.org/packages/CliFx)\n[![Discord](https://img.shields.io/discord/869237470565392384?label=discord)](https://discord.gg/2SUWKFnHSm)\n[![Fuck Russia](https://img.shields.io/badge/fuck-russia-e4181c.svg?labelColor=000000)](https://twitter.com/tyrrrz/status/1495972128977571848)\n\n\u003ctable\u003e\n    \u003ctr\u003e\n        \u003ctd width=\"99999\" align=\"center\"\u003eDevelopment of this project is entirely funded by the community. \u003cb\u003e\u003ca href=\"https://tyrrrz.me/donate\"\u003eConsider donating to support!\u003c/a\u003e\u003c/b\u003e\u003c/td\u003e\n    \u003c/tr\u003e\n\u003c/table\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003cimg src=\"favicon.png\" alt=\"Icon\" /\u003e\n\u003c/p\u003e\n\n**CliFx** is a simple to use, yet powerful framework for building command-line applications.\nIts primary goal is to completely take over the user input layer, allowing you to forget about infrastructural concerns and instead focus on writing your application.\n\n## Terms of use\u003csup\u003e[[?]](https://github.com/Tyrrrz/.github/blob/master/docs/why-so-political.md)\u003c/sup\u003e\n\nBy using this project or its source code, for any purpose and in any shape or form, you grant your **implicit agreement** to all the following statements:\n\n- You **condemn Russia and its military aggression against Ukraine**\n- You **recognize that Russia is an occupant that unlawfully invaded a sovereign state**\n- You **support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas**\n- You **reject false narratives perpetuated by Russian state propaganda**\n\nTo learn more about the war and how you can help, [click here](https://tyrrrz.me/ukraine). Glory to Ukraine! 🇺🇦\n\n## Install\n\n- 📦 [NuGet](https://nuget.org/packages/CliFx): `dotnet add package CliFx`\n\n## Features\n\n- Complete application framework, not just an argument parser\n- Minimum boilerplate and easy to get started\n- Class-first configuration via attributes\n- Comprehensive auto-generated help text\n- Support for deeply nested command hierarchies\n- Graceful cancellation via interrupt signals\n- Support for reading and writing binary data\n- Testable console interaction layer\n- Built-in analyzers to catch configuration issues\n- Targets .NET Standard 2.0+\n- No external dependencies\n\n## Screenshots\n\n![help screen](.assets/help-screen.png)\n\n## Usage\n\n### Quick overview\n\nTo turn your program into a command-line interface, modify the `Main()` method so that it delegates the execution to an instance of `CliApplication`.\nYou can use `CliApplicationBuilder` to simplify the process of creating and configuring an application:\n\n```csharp\nusing CliFx;\n\npublic static class Program\n{\n    public static async Task\u003cint\u003e Main() =\u003e\n        await new CliApplicationBuilder()\n            .AddCommandsFromThisAssembly()\n            .Build()\n            .RunAsync();\n}\n```\n\n\u003e **Warning**:\n\u003e Ensure that your `Main()` method returns the integer exit code provided by `CliApplication.RunAsync()`, as shown in the above example.\n\u003e Exit code is used to communicate execution result to the parent process, so it's important that your program propagates it.\n\n\u003e **Note**:\n\u003e When calling `CliApplication.RunAsync()`, **CliFx** resolves command-line arguments and environment variables from `Environment.GetCommandLineArgs()` and `Environment.GetEnvironmentVariables()` respectively.\n\u003e You can also provide them manually using one of the alternative overloads.\n\nThe code above uses `AddCommandsFromThisAssembly()` to detect command types defined within the current project and register them on the application.\nCommands are independent entry points, through which the user can interact with your program.\n\nTo define a command, create a class that implements the `ICommand` interface and annotate it with the `[Command]` attribute:\n\n```csharp\nusing CliFx;\nusing CliFx.Attributes;\n\n[Command(Description = \"Calculates the logarithm of a value.\")]\npublic class LogCommand : ICommand\n{\n    // Order: 0\n    [CommandParameter(0, Description = \"Value whose logarithm is to be found.\")]\n    public required double Value { get; init; }\n\n    // Name: --base\n    // Short name: -b\n    [CommandOption(\"base\", 'b', Description = \"Logarithm base.\")]\n    public double Base { get; init; } = 10;\n\n    public ValueTask ExecuteAsync(IConsole console)\n    {\n        var result = Math.Log(Value, Base);\n        console.Output.WriteLine(result);\n\n        // If the execution is not meant to be asynchronous,\n        // return an empty task at the end of the method.\n        return default;\n    }\n}\n```\n\nIn order to implement `ICommand`, the class needs to define an `ExecuteAsync(...)` method.\nThis is the method that gets called by the framework when the user decides to execute the command.\n\nAs the only parameter, this method takes an instance of `IConsole`, which is an abstraction around the system console.\nUse this abstraction in place of `System.Console` whenever you need to write output, read input, or otherwise interact with the console.\n\nIn most cases, you will also want to define input bindings, which are properties annotated by the `[CommandParameter]` and `[CommandOption]` attributes.\nThese bindings provide a way to map command-line arguments into structured input data that can be used by the command.\n\nThe command in the above example serves as a simple logarithm calculator and defines two inputs: a positional parameter for the input value and a named option for the logarithm base.\nIn order to execute this command, at minimum, the user needs to provide the input value:\n\n```console\n$ dotnet myapp.dll 10000\n\n4\n```\n\nThey can also pass the `-b|--base` option to override the default logarithm base of `10`:\n\n```console\n$ dotnet myapp.dll 729 -b 3\n\n6\n```\n\nIn case the user forgets to specify the required `value` parameter, the application will instead exit with an error:\n\n```console\n$ dotnet myapp.dll -b 10\n\nMissing required parameter(s):\n\u003cvalue\u003e\n```\n\nOut of the box, **CliFx** also provides a built-in `--help` option, which generates a help screen that lists all parameters and options available for the command:\n\n```console\n$ dotnet myapp.dll --help\n\nMyApp v1.0\n\nUSAGE\n  dotnet myapp.dll \u003cvalue\u003e [options]\n\nDESCRIPTION\n  Calculates the logarithm of a value.\n\nPARAMETERS\n* value             Value whose logarithm is to be found.\n\nOPTIONS\n  -b|--base         Logarithm base. Default: \"10\".\n  -h|--help         Shows help text.\n  --version         Shows version information.\n```\n\n### Argument syntax\n\nThis library employs a variation of the POSIX argument syntax, which is used in most modern command-line tools.\nHere are some examples of how it works:\n\n- `myapp --foo bar` sets option `\"foo\"` to value `\"bar\"`\n- `myapp -f bar` sets option `'f'` to value `\"bar\"`\n- `myapp --switch` sets option `\"switch\"` without value\n- `myapp -s` sets option `'s'` without value\n- `myapp -abc` sets options `'a'`, `'b'` and `'c'` without value\n- `myapp -xqf bar` sets options `'x'` and `'q'` without value, and option `'f'` to value `\"bar\"`\n- `myapp -i file1.txt file2.txt` sets option `'i'` to a sequence of values `\"file1.txt\"` and `\"file2.txt\"`\n- `myapp -i file1.txt -i file2.txt` sets option `'i'` to a sequence of values `\"file1.txt\"` and `\"file2.txt\"`\n- `myapp cmd abc -o` routes to command `cmd` (assuming it's a command) with parameter `abc` and sets option `'o'` without value\n\nAdditionally, argument parsing in **CliFx** aims to be as deterministic as possible, ideally yielding the same result regardless of the application configuration.\nIn fact, the only context-sensitive part in the parser is the command name resolution, which needs to know the list of available commands in order to discern them from parameters.\n\nThe parser's context-free nature has several implications on how it consumes arguments.\nFor example, `myapp -i file1.txt file2.txt` will always be parsed as an option with multiple values, regardless of the arity of the underlying property it's bound to.\nSimilarly, unseparated arguments in the form of `myapp -ofile` will be treated as five distinct options `'o'`, `'f'`, `'i'`, `'l'`, `'e'`, instead of `'o'` being set to value `\"file\"`.\n\nThese rules also make the order of arguments important — command-line string is expected to follow this pattern:\n\n```console\n$ myapp [...directives] [command] [...parameters] [...options]\n```\n\n### Parameters and options\n\n**CliFx** supports two types of argument bindings: **parameters** and **options**.\nParameters are bound from the command-line arguments based on the order they appear in, while options are bound by their name.\n\nBesides that, they also differ in the following ways:\n\n- Parameters are required by default, while options are not.\n\n  - You can make an option required by setting `IsRequired = true` on the corresponding attribute or by adding the `required` keyword to the property declaration (introduced in C# 11):\n\n    ```csharp\n    // Any option can be required or optional without restrictions\n    [CommandOption(\"foo\")]\n    public required string RequiredOption { get; init; }\n    ```\n\n  - To make a parameter optional, you can set `IsRequired = false`, but only the last parameter (by order) can be configured in such way:\n\n    ```csharp\n    // Only the last parameter can be optional\n    [CommandParameter(0, IsRequired = false)]\n    public string? OptionalParameter { get; init; }\n    ```\n\n- Parameters are primarily used for scalar (non-enumerable) properties, while options can be used for both scalar and non-scalar properties.\n\n  - You can bind an option to a property of a non-scalar type, such as `IReadOnlyList\u003cT\u003e`:\n\n    ```csharp\n    // Any option can be non-scalar\n    [CommandOption(\"foo\")]\n    public required IReadOnlyList\u003cstring\u003e NonScalarOption { get; init; }\n    ```\n\n  - You can bind a parameter to a non-scalar property, but only if it's the last parameter in the command:\n\n    ```csharp\n    // Only the last parameter can be non-scalar\n    [CommandParameter(0)]\n    public required IReadOnlyList\u003cstring\u003e NonScalarParameter { get; init; }\n    ```\n\n- Options can rely on an environment variable for fallback, while parameters cannot:\n\n  ```csharp\n  // If the value is not provided directly, it will be read\n  // from the environment variable instead.\n  // This works for both scalar and non-scalar properties.\n  [CommandOption(\"foo\", EnvironmentVariable = \"ENV_FOO\")]\n  public required string OptionWithFallback { get; init; }\n  ```\n\n\u003e **Note**:\n\u003e **CliFx** has a set of built-in analyzers that detect common errors in command definitions.\n\u003e Your code will not compile if a command contains duplicate options, overlapping parameters, or otherwise invalid configuration.\n\n### Value conversion\n\nParameters and options can be bound to properties with the following underlying types:\n\n- Basic types\n  - Primitive types (`int`, `bool`, `double`, `ulong`, `char`, etc.)\n  - Date and time types (`DateTime`, `DateTimeOffset`, `TimeSpan`)\n  - Enum types (converted from either name or numeric value)\n- String-initializable types\n  - Types with a constructor accepting a `string` (`FileInfo`, `DirectoryInfo`, etc.)\n  - Types with a static `Parse(...)` method accepting a `string` and optionally a `IFormatProvider` (`Guid`, `BigInteger`, etc.)\n- Nullable versions of all above types (`decimal?`, `TimeSpan?`, etc.)\n- Any other type if a custom converter is specified\n- Collections of all above types\n  - Array types (`T[]`)\n  - Types that are assignable from arrays (`IReadOnlyList\u003cT\u003e`, `ICollection\u003cT\u003e`, etc.)\n  - Types with a constructor accepting an array (`List\u003cT\u003e`, `HashSet\u003cT\u003e`, etc.)\n\n#### Non-scalar parameters and options\n\nHere's an example of a command with an array-backed parameter:\n\n```csharp\n[Command]\npublic class FileSizeCalculatorCommand : ICommand\n{\n    // FileInfo is string-initializable and IReadOnlyList\u003cT\u003e can be assigned from an array,\n    // so the value of this property can be mapped from a sequence of arguments.\n    [CommandParameter(0)]\n    public required IReadOnlyList\u003cFileInfo\u003e Files { get; init; }\n\n    public ValueTask ExecuteAsync(IConsole console)\n    {\n        var totalSize = Files.Sum(f =\u003e f.Length);\n        console.Output.WriteLine($\"Total file size: {totalSize} bytes\");\n\n        return default;\n    }\n}\n```\n\n```console\n$ dotnet myapp.dll file1.bin file2.exe\n\nTotal file size: 186368 bytes\n```\n\n#### Custom conversion\n\nTo create a custom converter for a parameter or an option, define a class that inherits from `BindingConverter\u003cT\u003e` and specify it in the attribute:\n\n```csharp\n// Maps 2D vectors from AxB notation\npublic class VectorConverter : BindingConverter\u003cVector2\u003e\n{\n    public override Vector2 Convert(string? rawValue)\n    {\n        if (string.IsNullOrWhiteSpace(rawValue))\n            return default;\n\n        var components = rawValue.Split('x', 'X', ';');\n        var x = int.Parse(components[0], CultureInfo.InvariantCulture);\n        var y = int.Parse(components[1], CultureInfo.InvariantCulture);\n\n        return new Vector2(x, y);\n    }\n}\n\n[Command]\npublic class SurfaceCalculatorCommand : ICommand\n{\n    // Custom converter is used to map raw argument values\n    [CommandParameter(0, Converter = typeof(VectorConverter))]\n    public required Vector2 PointA { get; init; }\n\n    [CommandParameter(1, Converter = typeof(VectorConverter))]\n    public required Vector2 PointB { get; init; }\n\n    [CommandParameter(2, Converter = typeof(VectorConverter))]\n    public required Vector2 PointC { get; init; }\n\n    public ValueTask ExecuteAsync(IConsole console)\n    {\n        var a = (PointB - PointA).Length();\n        var b = (PointC - PointB).Length();\n        var c = (PointA - PointC).Length();\n\n        var p = (a + b + c) / 2;\n        var surface = Math.Sqrt(p * (p - a) * (p - b) * (p - c));\n\n        console.Output.WriteLine($\"Triangle surface area: {surface}\");\n\n        return default;\n    }\n}\n```\n\n```console\n$ dotnet myapp.dll 0x0 0x10 10x0\n\nTriangle surface area: 50\n```\n\n### Multiple commands\n\nIn order to facilitate a variety of different workflows, command-line applications may provide the user with more than just a single command.\nComplex applications may also nest commands underneath each other, employing a multi-level hierarchical structure.\n\nWith **CliFx**, this is achieved by simply giving each command a unique name through the `[Command]` attribute.\nCommands that have common name segments are considered to be hierarchically related, which affects how they're listed in the help text.\n\n```csharp\n// Default command, i.e. command without a name\n[Command]\npublic class DefaultCommand : ICommand\n{\n    // ...\n}\n\n// Child of default command\n[Command(\"cmd1\")]\npublic class FirstCommand : ICommand\n{\n    // ...\n}\n\n// Child of default command\n[Command(\"cmd2\")]\npublic class SecondCommand : ICommand\n{\n    // ...\n}\n\n// Child of FirstCommand\n[Command(\"cmd1 sub\")]\npublic class SubCommand : ICommand\n{\n    // ...\n}\n```\n\nOnce configured, the user can execute a specific command by prepending its name to the passed arguments.\nFor example, running `dotnet myapp.dll cmd1 arg1 -p 42` will execute `FirstCommand` in the above example.\n\nThe user can also find the list of all available top-level commands in the help text:\n\n```console\n$ dotnet myapp.dll --help\n\nMyApp v1.0\n\nUSAGE\n  dotnet myapp.dll [options]\n  dotnet myapp.dll [command] [...]\n\nOPTIONS\n  -h|--help         Shows help text.\n  --version         Shows version information.\n\nCOMMANDS\n  cmd1              Subcommands: cmd1 sub.\n  cmd2\n\nYou can run `dotnet myapp.dll [command] --help` to show help on a specific command.\n```\n\nTo see the list of commands nested under a specific command, the user can refine their help request by specifying the corresponding command name before the help option:\n\n```console\n$ dotnet myapp.dll cmd1 --help\n\nUSAGE\n  dotnet myapp.dll cmd1 [options]\n  dotnet myapp.dll cmd1 [command] [...]\n\nOPTIONS\n  -h|--help         Shows help text.\n\nCOMMANDS\n  sub\n\nYou can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific command.\n```\n\n\u003e **Note**:\n\u003e Defining the default (unnamed) command is not required.\n\u003e If it's absent, running the application without specifying a command will just show the root-level help text.\n\n### Reporting errors\n\nCommands in **CliFx** do not directly return exit codes, but instead communicate execution errors via `CommandException`.\nThis special exception type can be used to print an error message to the console, return a specific exit code, and also optionally show help text for the current command:\n\n```csharp\n[Command]\npublic class DivideCommand : ICommand\n{\n    [CommandOption(\"dividend\")]\n    public required double Dividend { get; init; }\n\n    [CommandOption(\"divisor\")]\n    public required double Divisor { get; init; }\n\n    public ValueTask ExecuteAsync(IConsole console)\n    {\n        if (Math.Abs(Divisor) \u003c double.Epsilon)\n        {\n            // This will print the error and set exit code to 133\n            throw new CommandException(\"Division by zero is not supported.\", 133);\n        }\n\n        var result = Dividend / Divisor;\n        console.Output.WriteLine(result);\n\n        return default;\n    }\n}\n```\n\n```console\n$ dotnet myapp.dll --dividend 10 --divisor 0\n\nDivision by zero is not supported.\n\n$ echo $?\n\n133\n```\n\n\u003e **Warning**:\n\u003e Even though exit codes are represented by 32-bit integers in .NET, using values outside the 8-bit unsigned range will cause overflows on Unix systems.\n\u003e To avoid unexpected results, use numbers between 1 and 255 for exit codes that indicate failure.\n\n### Graceful cancellation\n\nConsole applications support the concept of interrupt signals, which can be issued by the user to abort the currently ongoing operation.\nIf your command performs critical work, you can intercept these signals to handle cancellation requests in a graceful way.\n\nIn order to make the command cancellation-aware, call `console.RegisterCancellationHandler()` to register the signal handler and obtain the corresponding `CancellationToken`.\nOnce this method is called, the program will no longer terminate on an interrupt signal but will instead trigger the associated token, which can be used to delay the termination of a command just enough to exit in a controlled manner.\n\n```csharp\n[Command]\npublic class CancellableCommand : ICommand\n{\n    private async ValueTask DoSomethingAsync(CancellationToken cancellation)\n    {\n        await Task.Delay(TimeSpan.FromMinutes(10), cancellation);\n    }\n\n    public async ValueTask ExecuteAsync(IConsole console)\n    {\n        // Make the command cancellation-aware\n        var cancellation = console.RegisterCancellationHandler();\n\n        // Execute some long-running cancellable operation\n        await DoSomethingAsync(cancellation);\n\n        console.Output.WriteLine(\"Done.\");\n    }\n}\n```\n\n\u003e **Warning**:\n\u003e Cancellation handler is only respected when the user sends the interrupt signal for the first time.\n\u003e If the user decides to issue the signal again, the application will be forcefully terminated without triggering the cancellation token.\n\n### Type activation\n\nBecause **CliFx** takes responsibility for the application's entire lifecycle, it needs to be capable of instantiating various user-defined types at run-time.\nTo facilitate that, it uses an interface called `ITypeActivator` that determines how to create a new instance of a given type.\n\nThe default implementation of `ITypeActivator` only supports types that have public parameterless constructors, which is sufficient for the majority of scenarios.\nHowever, in some cases you may also want to define a custom initializer, for example when integrating with an external dependency container.\n\nTo do that, pass a custom `ITypeActivator` or a factory delegate to the `UseTypeActivator(...)` method when building the application:\n\n```csharp\npublic static class Program\n{\n    public static async Task\u003cint\u003e Main() =\u003e\n        await new CliApplicationBuilder()\n            .AddCommandsFromThisAssembly()\n            .UseTypeActivator(type =\u003e\n            {\n                var instance = MyTypeFactory.Create(type);\n                return instance;\n            })\n            .Build()\n            .RunAsync();\n}\n```\n\nThis method also supports `IServiceProvider` through various overloads, which allows you to directly integrate dependency containers that implement this interface.\nFor example, this is how to configure your application to use [`Microsoft.Extensions.DependencyInjection`](https://nuget.org/packages/Microsoft.Extensions.DependencyInjection) as the type activator in **CliFx**:\n\n```csharp\npublic static class Program\n{\n    public static async Task\u003cint\u003e Main() =\u003e\n        await new CliApplicationBuilder()\n            .AddCommandsFromThisAssembly()\n            .UseTypeActivator(commandTypes =\u003e\n            {\n                var services = new ServiceCollection();\n\n                // Register services\n                services.AddSingleton\u003cMyService\u003e();\n\n                // Register commands\n                foreach (var commandType in commandTypes)\n                    services.AddTransient(commandType);\n\n                return services.BuildServiceProvider();\n            })\n            .Build()\n            .RunAsync();\n}\n```\n\n\u003e **Note**:\n\u003e If you want to use certain advanced features provided by `Microsoft.Extensions.DependencyInjection`, you may need to do a bit of extra work to configure the container properly.\n\u003e For example, to leverage support for keyed services, you need to [manually register an implementation of `IKeyedServiceProvider`](https://github.com/Tyrrrz/CliFx/issues/148).\n\n### Testing\n\nThanks to the `IConsole` abstraction, **CliFx** commands can be easily tested in isolation.\nWhile an application running in production would rely on `SystemConsole` to interact with the real console, you can use `FakeConsole` and `FakeInMemoryConsole` in your tests to execute your commands in a simulated environment.\n\nFor example, imagine you have the following command:\n\n```csharp\n[Command]\npublic class ConcatCommand : ICommand\n{\n    [CommandOption(\"left\")]\n    public string Left { get; init; } = \"Hello\";\n\n    [CommandOption(\"right\")]\n    public string Right { get; init; } = \"world\";\n\n    public ValueTask ExecuteAsync(IConsole console)\n    {\n        console.Output.Write(Left);\n        console.Output.Write(' ');\n        console.Output.Write(Right);\n\n        return default;\n    }\n}\n```\n\nTo test it, you can instantiate the command in code with the required values, and then pass an instance of `FakeInMemoryConsole` to `ExecuteAsync(...)`:\n\n```csharp\n// Integration test at the command level\n[Test]\npublic async Task ConcatCommand_executes_successfully()\n{\n    // Arrange\n    using var console = new FakeInMemoryConsole();\n\n    var command = new ConcatCommand\n    {\n        Left = \"foo\",\n        Right = \"bar\"\n    };\n\n    // Act\n    await command.ExecuteAsync(console);\n\n    // Assert\n    var stdOut = console.ReadOutputString();\n    Assert.That(stdOut, Is.EqualTo(\"foo bar\"));\n}\n```\n\nSimilarly, you can also test your command at a higher level like so:\n\n```csharp\n// End-to-end test at the application level\n[Test]\npublic async Task ConcatCommand_executes_successfully()\n{\n    // Arrange\n    using var console = new FakeInMemoryConsole();\n\n    var app = new CliApplicationBuilder()\n        .AddCommand\u003cConcatCommand\u003e()\n        .UseConsole(console)\n        .Build();\n\n    var args = new[]\n    {\n        \"--left\", \"foo\",\n        \"--right\", \"bar\"\n    };\n\n    var envVars = new Dictionary\u003cstring, string\u003e();\n\n    // Act\n    await app.RunAsync(args, envVars);\n\n    // Assert\n    var stdOut = console.ReadOutputString();\n    Assert.That(stdOut, Is.EqualTo(\"foo bar\"));\n}\n```\n\n### Debug and preview mode\n\nWhen troubleshooting issues, you may find it useful to run your app in debug or preview mode.\nTo do that, pass the corresponding directive before any other command-line arguments.\n\nIn order to run the application in debug mode, use the `[debug]` directive.\nThis will cause the program to launch in a suspended state, waiting for the debugger to attach to the current process:\n\n```console\n$ dotnet myapp.dll [debug] cmd -o\n\nAttach debugger to PID 3148 to continue.\n```\n\nTo run the application in preview mode, use the `[preview]` directive.\nThis will short-circuit the execution and instead print the consumed command-line arguments as they were parsed, along with resolved environment variables:\n\n```console\n$ dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2\n\nCommand-line:\n  cmd \u003carg1\u003e \u003carg2\u003e [-o foo] [--option bar1 bar2]\n\nEnvironment:\n  FOO=\"123\"\n  BAR=\"xyz\"\n```\n\nYou can also disallow these directives, e.g. when running in production, by calling `AllowDebugMode(...)` and `AllowPreviewMode(...)` methods on `CliApplicationBuilder`:\n\n```csharp\nvar app = new CliApplicationBuilder()\n    .AddCommandsFromThisAssembly()\n    .AllowDebugMode(true) // allow debug mode\n    .AllowPreviewMode(false) // disallow preview mode\n    .Build();\n```\n\n## Etymology\n\n**CliFx** is made out of \"Cli\" for \"Command-line Interface\" and \"Fx\" for \"Framework\".\nIt's pronounced as \"cliff ex\".\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftyrrrz%2Fclifx","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftyrrrz%2Fclifx","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftyrrrz%2Fclifx/lists"}