### Link output example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-writer.md Example of writing a hyperlink using WriteLink with a CliLink and a format string. ```csharp Cli.Output.WriteLink(new CliLink("https://dotmake.build/command-line/"), "Docs: {0}", "DotMake Command-Line"); ``` -------------------------------- ### Example: Run with custom settings Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-parser.md Example of running with custom settings. The CliSettings configure the default exception handler, diagram directive, and process termination timeout. ```csharp var parser = Cli.GetParser(new CliSettings { EnableDefaultExceptionHandler = true, EnableDiagramDirective = true, ProcessTerminationTimeout = TimeSpan.FromSeconds(5) }); int exitCode = parser.Run(args); return exitCode; ``` -------------------------------- ### Example: RunAsync with cancellation token Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-parser.md Example of running asynchronously with a cancellation token. The token can be used to cancel the invocation. ```csharp using var cts = new CancellationTokenSource(); var parser = Cli.GetParser(); int exitCode = await parser.RunAsync(args, cts.Token); ``` -------------------------------- ### ShowHierarchy(bool showLevel) method and usage example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-context.md Prints a tree of all commands starting from the root command (depth-first, tree-drawing characters ├╴, └╴, │), each node styled with the theme's first-column style; level labels styled with the second-column style. The showLevel parameter (default false) controls whether level labels are shown. The example shows the expected output with level labels. ```csharp public void ShowHierarchy(bool showLevel = false) ``` ```csharp public void Run(CliContext context) { context.ShowHierarchy(showLevel: true); // myapp (level 0) // ├╴level-1 (level 1) // │ └╴level-2 (level 2) // └╴level-1b (level 1) } ``` -------------------------------- ### Custom help via settings Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Example showing how to customize help output via CliSettings and CliTheme. ```APIDOC ## CliSettings ### Description Settings for configuring the CLI help output. The example shows customizing the theme for help output. ### Example ```csharp var settings = new CliSettings { Theme = new CliTheme(CliTheme.Default) { HeadingCasing = CliNameCasingConvention.UpperCase, HeadingNoColon = true, } }; Cli.Run(new[] { "--help" }, settings); ``` ``` -------------------------------- ### Install DotMake.CommandLine via dotnet CLI Source: https://github.com/dotmake-build/command-line/blob/main/README.md Install the DotMake.CommandLine NuGet package into your console app project using the .NET CLI. ```console dotnet add package DotMake.CommandLine ``` -------------------------------- ### CliStringUtil name conversion example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/validation-and-naming.md Example usage of CliStringUtil methods for name conversion and prefix handling. Demonstrates ToCase with KebabCase and SnakeCase, AddPrefix with DoubleHyphen, RemovePrefix, and SplitPrefix returning a tuple. ```csharp Console.WriteLine(CliStringUtil.ToCase("searchPath", CliNameCasingConvention.KebabCase)); // search-path Console.WriteLine(CliStringUtil.ToCase("search path", CliNameCasingConvention.SnakeCase)); // search_path Console.WriteLine(CliStringUtil.AddPrefix("input", CliNamePrefixConvention.DoubleHyphen)); // --input Console.WriteLine(CliStringUtil.RemovePrefix("--output")); // output var (prefix, alias) = CliStringUtil.SplitPrefix("/verbose"); // ("//", "verbose") ``` -------------------------------- ### Fluent style construction example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-writer.md Example of fluent style construction using StyleExtensions to create a CliStyle with white foreground, red background, and bold decoration. ```csharp CliStyle error = new CliStyle() .Foreground(CliColor.White) .Background(CliColor.Red) .Decoration(CliDecoration.Bold); ``` -------------------------------- ### [suggest] directive example with output Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/directives.md Shows the [suggest] directive usage and its output. The directive searches for commands that match the given prefix and returns a list of suggestions. ```console dotnet [suggest] buil ``` ```console build build-server msbuild ``` -------------------------------- ### Parse and bind with returnEmpty example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-result.md Parses without running, then binds the root command and a subcommand. Uses returnEmpty: true to get an empty instance when the subcommand is absent. ```csharp var result = Cli.Parse(args); var root = result.Bind(); if (root != null) { Console.WriteLine($"Option1 = {root.Option1}"); } // Bind a subcommand even when a sibling was called; empty instance when absent: var level1 = result.Bind(returnEmpty: true); ``` -------------------------------- ### Sample usage and output for custom directives Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/directives.md Sample usage and output for the custom directive example. Shows how directives with arguments are passed and the resulting output for each directive property. ```console src\TestApp\bin\Debug\net8.0>TestApp [debug] [directive-2:val1] [vars:val2] [vars:val3] Directive 'Debug' = true Directive 'Directive2' = "val1" Directive 'Vars' = ["val2", "val3"] ``` -------------------------------- ### Equivalent Boolean option examples Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/arguments.md Two equivalent command-line examples showing that many options are implicitly Boolean parameters with a default of `true` when the option name is present. The first omits the argument, the second explicitly passes `true`. ```console dotnet tool update dotnet-suggest --global ^------^ dotnet tool update dotnet-suggest --global true ^-----------^ ``` -------------------------------- ### Cli.Run string overload example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli.md Example of calling the string overload with a command line string that includes an argument value and an option flag. ```csharp Cli.Run("NewValueForArgument1 --option-1"); ``` -------------------------------- ### Install Microsoft.Extensions.DependencyInjection.Abstractions package Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/dependency-injection.md Install the Microsoft.Extensions.DependencyInjection.Abstractions package (version >= 2.1.1) to support custom service providers. This package enables the source generator to create extension methods for setting a custom service provider. ```console dotnet add package Microsoft.Extensions.DependencyInjection.Abstractions ``` ```console PM> Install-Package Microsoft.Extensions.DependencyInjection.Abstractions ``` -------------------------------- ### Diagnostic output example (DMCLI22, DMCLI24) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/source-generator.md Shows example build output with error DMCLI22 and warning DMCLI24 from the source generator. Use to recognize expected diagnostics when a command class lacks a parameterless constructor or a handler method. ```console error DMCLI22: DotMake.CommandLine.SourceGeneration -> The class 'BrokenCliCommand' must have a parameterless (default) and public/internal and non-static constructor to generate a command builder when not using dependency injection. warning DMCLI24: DotMake.CommandLine.SourceGeneration -> The class 'NoHandlerCliCommand' will not have a command handler (ignored) because it does not have a method with one of the following signatures: 'void Run()', 'int Run()', ... ``` -------------------------------- ### Cli.RunAsync async lambda example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli.md Example of calling Cli.RunAsync with an async lambda that returns an exit code after a delay. ```csharp return await Cli.RunAsync(async ([CliArgument] string argument1, bool option1) => { await Task.Delay(1000); return 0; }); ``` -------------------------------- ### ShowHelp() method and usage example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-context.md Shows help for the current command by invoking the help option's SynchronousCommandLineAction (CustomHelpAction) with the parse result. Uses the root command's HelpOption, falling back to the current command's, then to a default HelpOption with a CliHelpBuilder(CliTheme.Default). The example demonstrates calling context.ShowHelp() to print help instead of running when a required option is missing. ```csharp public void ShowHelp() ``` ```csharp [CliCommand(Description = "Greet command")] public class GreetCliCommand { [CliOption(Description = "Name to greet")] public string Name { get; set; } = "World"; public void Run(CliContext context) { if (string.IsNullOrEmpty(Name)) { context.ShowHelp(); // print help instead of running return; } Console.WriteLine($"Hello, {Name}!"); } } ``` -------------------------------- ### HelpBuilder.Default.OptionsSection() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the options section writer. ```APIDOC ## [GET] HelpBuilder.Default.OptionsSection() ### Description Gets the options section writer. ### Method GET ### Endpoint HelpBuilder.Default.OptionsSection() ### Parameters None ### Response #### Success Response - **Func** - The section writer. ``` -------------------------------- ### [env] directive syntax examples Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/directives.md Shows the [env] directive syntax for setting environment variables from the command line. Multiple environment variables can be set with separate directives. ```console myapp [env:key=value] ``` ```console myapp [env:key1=value1] [env:key2=value2] ``` -------------------------------- ### Help output showing dynamic completions Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/completions.md Example help output showing the dynamic completion values for the DateOption and FruitArgument. The completions appear as alternatives in the help text, demonstrating that the dynamic list is also reflected in the help output. ```console DotMake Command-Line TestApp v3.7.0 Copyright © 2023-2026 DotMake A root cli command with completions for options and arguments Usage: TestApp [] [options] Arguments: Description for FruitArgument [default: DefaultForFruitArgument] Options: -d, --date Description for DateOption <10.09.2026|11.09.2026|12.09.2026|13.09.2026|7.09.2026|8.0 9.2026|9.09.2026> -?, -h, --help Show help and usage information -v, --version Show version information ``` -------------------------------- ### Delegate-based Cli.Run example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli.md Demonstrates the delegate-based model for Cli.Run. Shows both a lambda with auto-detected option and a method reference with explicit [CliArgument] and [CliOption] attributes. ```csharp // In Program.cs Cli.Run(([CliArgument] string argument1, bool option1) => { Console.WriteLine($"Value for {nameof(argument1)} parameter is '{argument1}'"); Console.WriteLine($"Value for {nameof(option1)} parameter is '{option1}'"); }); // Or pass a method reference: Cli.Run(Method); void Method([CliArgument] string argument2, [CliOption] bool option2) { Console.WriteLine($"Value for {nameof(argument2)} parameter is '{argument2}'"); } ``` -------------------------------- ### HelpBuilder.Default.GetOptionUsageLabel(Option) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the first-column usage text for an option. ```APIDOC ## [GET] HelpBuilder.Default.GetOptionUsageLabel(Option) ### Description Gets the first-column usage text for an option. ### Method GET ### Endpoint HelpBuilder.Default.GetOptionUsageLabel(Option) ### Parameters #### Method Parameters - **symbol** (Option) - Required - The option to get the usage label for. ### Response #### Success Response - **string** - The usage label. ``` -------------------------------- ### Example of Windows-style option with leading slash Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/options.md Illustrates the Windows prefix convention using a leading slash (/) before the option name. ```console msbuild /version ^------^ ``` -------------------------------- ### Help output for a root CLI command Source: https://github.com/dotmake-build/command-line/blob/main/README.md Example help output generated by DotMake.CommandLine when running the app with -? or dotnet run -- -?. Shows auto-generated usage, argument and option names, descriptions, and default values. ```console DotMake Command-Line TestApp v3.7.0 Copyright © 2023-2026 DotMake A root cli command Usage: TestApp [] [options] Arguments: Description for Argument1 [default: DefaultForArgument1] Options: -o, --option-1 Description for Option1 [default: False] -?, -h, --help Show help and usage information -v, --version Show version information ``` -------------------------------- ### Customizing symbol help text Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Example showing how to customize symbol help text programmatically using CustomHelpAction.Builder.CustomizeSymbol. ```APIDOC ## CustomHelpAction.Builder.CustomizeSymbol ### Description Customizes the help text for a specific symbol (e.g., an option) programmatically. ### Example ```csharp var parser = Cli.GetParser(); var command = parser.Command; // Find the option created from the `Option1` property: var option = command.Options.Single(o => o.Name == "--option-1"); var helpAction = (CustomHelpAction)parser.RootCommand.Options .First(o => o is HelpOption).Action; helpAction.Builder.CustomizeSymbol(option, firstColumnText: "-o, --option-1 ", secondColumnText: "Custom description for option-1"); var result = parser.Run(new[] { "--help" }); ``` ``` -------------------------------- ### Custom Completions Example for SearchCliCommand Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/handler-interfaces.md Shows how to implement ICliGetCompletions in a CLI command class. The GetCompletions method yields completion items for the Engine option, providing 'google', 'bing', and 'duckduckgo' as suggestions. ```csharp using System.CommandLine.Completions; [CliCommand] public class SearchCliCommand : ICliGetCompletions { [CliOption(Description = "Search engine")] public string Engine { get; set; } public IEnumerable GetCompletions(string propertyName, CompletionContext completionContext) { switch (propertyName) { case nameof(Engine): yield return new CompletionItem("google"); yield return new CompletionItem("bing"); yield return new CompletionItem("duckduckgo"); break; } } } ``` -------------------------------- ### Styled output example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-writer.md Example of styled output using CliWriter. Shows writing to standard output with green bold text, writing to error output with red text and a format argument, and applying a persistent underline style followed by a reset. ```csharp using DotMake.CommandLine; Cli.Output.WriteLine(CliStyle.Plain.Foreground(CliColor.Green).Decoration(CliDecoration.Bold), "Build succeeded!"); Cli.Error.WriteLine(CliStyle.Plain.Foreground(CliColor.Red), "Error: {0}", message); // persistent style + reset: Cli.Output .SetStyle(new CliStyle().Decoration(CliDecoration.Underline)) .Write("Header"); Cli.Output.ResetStyle(); ``` -------------------------------- ### ShowValues() method and usage example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-context.md Prints parsed values for the current and parent commands, their arguments and options, and (for the root) directive values — useful for testing a command. Output is written to Output using the theme's FirstColumnStyle/SecondColumnStyle (falls back to DefaultStyle). The example shows the expected output format. ```csharp public void ShowValues() ``` ```csharp public void Run(CliContext context) { // myapp --option-1 value arg1 // prints: // Root Command: myapp // Argument 'argument-1': arg1 // Option '--option-1': value context.ShowValues(); } ``` -------------------------------- ### HelpBuilder.Default.GetLayout() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the default section layout. ```APIDOC ## [GET] HelpBuilder.Default.GetLayout() ### Description Gets the default section layout. ### Method GET ### Endpoint HelpBuilder.Default.GetLayout() ### Parameters None ### Response #### Success Response - **IEnumerable>** - The default sections in order. ``` -------------------------------- ### Install Microsoft.Extensions.DependencyInjection package Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/dependency-injection.md Install the Microsoft.Extensions.DependencyInjection package (version >= 2.1.1) using either the .NET CLI or the Visual Studio Package Manager Console. This package enables the source generator to create extension methods for dependency injection. ```console dotnet add package Microsoft.Extensions.DependencyInjection ``` ```console PM> Install-Package Microsoft.Extensions.DependencyInjection ``` -------------------------------- ### Basic usage of Cli.Run Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli.md Example showing a root command class with a CliCommand attribute, an argument, an option, and a Run method. The Program.Main method calls Cli.Run(args). ```csharp using System; using DotMake.CommandLine; namespace MyApp; [CliCommand(Description = "A root cli command")] public class RootCliCommand { [CliArgument(Description = "Description for Argument1")] public string Argument1 { get; set; } = "DefaultForArgument1"; [CliOption(Description = "Description for Option1")] public bool Option1 { get; set; } public void Run() { Console.WriteLine($"Value for {nameof(Option1)} property is '{Option1}'"); Console.WriteLine($"Value for {nameof(Argument1)} property is '{Argument1}'"); } } public class Program { public static int Main(string[] args) { return Cli.Run(args); } } ``` -------------------------------- ### Async flow with cancellation using RunAsync Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-result.md Example of an async flow with cancellation. It creates a 30-second cancellation token source, parses a DownloadCliCommand, and runs it asynchronously with the token. ```csharp using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var result = Cli.Parse(args); return await result.RunAsync(cts.Token); ``` -------------------------------- ### Non-trivial layout customization Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Example showing non-trivial layout customization using CliHelpBuilder.CustomizeLayout. ```APIDOC ## CliHelpBuilder.CustomizeLayout ### Description Customizes the layout of the help output by specifying which sections to write. ### Example ```csharp Cli.GetParser(); var parser = Cli.GetParser(); var helpAction = (CustomHelpAction)parser.RootCommand.Options.First(o => o is HelpOption).Action; if (helpAction.Builder is CliHelpBuilder cliBuilder) { cliBuilder.CustomizeLayout(ctx => { yield return cliBuilder.WriteCommandUsageSection; yield return cliBuilder.WriteCommandOptionsSection; // skip arguments & subcommands sections }); } ``` ``` -------------------------------- ### Register services with Cli.Ext.ConfigureServices Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/dependency-injection.md Register services with the generated extension method Cli.Ext.ConfigureServices. This method is available when the project references Microsoft.Extensions.DependencyInjection. The example registers transient, scoped, and singleton services before running the command. ```csharp using DotMake.CommandLine; using Microsoft.Extensions.DependencyInjection; Cli.Ext.ConfigureServices(services => { services.AddTransient(); services.AddScoped(); services.AddSingleton(); }); Cli.Run(); ``` -------------------------------- ### Async handler with cancellation using Cli.RunAsync Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli.md Example showing an async command handler that uses CliContext.CancellationToken, and a Program.cs call to Cli.RunAsync with a cancellation token. ```csharp [CliCommand] public class AsyncCliCommand { public async Task RunAsync(CliContext context) { // context.CancellationToken arrives from Cli.RunAsync's token await Task.Delay(1000, context.CancellationToken); return 0; } } // Program.cs var exitCode = await Cli.RunAsync(args, cancellationToken: token); ``` -------------------------------- ### Example of [diagram] directive with output Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/directives.md Shows the command line with the [diagram] directive and the resulting parse diagram. The caret line marks the directive token. The output shows how the command, options, and values are grouped in brackets. ```console dotnet [diagram] build --no-restore --output ./build-output/ ^-------^ ``` ```console [ dotnet [ build [ --no-restore ] [ --output <./build-output/> ] ] ] ``` -------------------------------- ### CliParser.Command property Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-parser.md Gets the command that parses the command-line input. Use it to interact with the underlying System.CommandLine model, for example via Command.Parse. ```csharp public Command Command { get; } ``` -------------------------------- ### Register services and run with Cli.Ext.ConfigureServices Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/dependency-injection.md Configures the service collection with transient, scoped, and singleton services, then runs the root command. Requires the DotMake.CommandLine and Microsoft.Extensions.DependencyInjection namespaces. ```csharp using DotMake.CommandLine; using Microsoft.Extensions.DependencyInjection; Cli.Ext.ConfigureServices(services => { services.AddTransient(); services.AddScoped(); services.AddSingleton(); }); return Cli.Run(); ``` -------------------------------- ### Custom help via settings Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Configures help output via CliSettings with a custom theme. Already wired by default. ```csharp var settings = new CliSettings { Theme = new CliTheme(CliTheme.Default) { HeadingCasing = CliNameCasingConvention.UpperCase, HeadingNoColon = true, } }; Cli.Run(new[] { "--help" }, settings); ``` -------------------------------- ### CountingWriter subclass example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-writer.md Example subclass that observes writes by incrementing a counter before delegating to the base writer. ```csharp public class CountingWriter : DelegatingTextWriter { public int Count { get; private set; } public CountingWriter(TextWriter inner) : base(inner) { } public override void Write(string value) { Count++; base.Write(value); } } ``` -------------------------------- ### Running the application with arguments Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/model-binding.md Shows how to run the application with a command-line argument, either directly or via dotnet run with a double dash. The output displays the bound values for Option1 and Argument1. ```console TestApp.exe NewValueForArgument1 ``` ```console dotnet run -- NewValueForArgument1 ``` ```console Handler for 'TestApp.Commands.RootCliCommand' is run: Value for Option1 property is 'DefaultForOption1' Value for Argument1 property is 'NewValueForArgument1' ``` -------------------------------- ### CliColor usage example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-writer.md Example of color usage: writing colored text with Cli.Output.WriteLine, and implicit conversions between CliColor and ConsoleColor. ```csharp Cli.Output.WriteLine(CliColor.FromHex("#FF8800"), "Orange text"); Cli.Output.WriteLine(CliColor.Red, "Red text"); ConsoleColor cc = CliColor.DarkGreen; // implicit conversion CliColor back = ConsoleColor.Yellow; // implicit conversion ``` -------------------------------- ### Configure theme with object initializer Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-theme.md Shows how to create a CliTheme using an object initializer, setting HeadingStyle to yellow and FirstColumnStyle to cyan with plain foreground. ```csharp var theme = new CliTheme { HeadingStyle = CliColor.Yellow, FirstColumnStyle = CliStyle.Plain.Foreground(CliColor.Cyan) }; ``` -------------------------------- ### BindCalled() usage example Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-result.md Binds the deepest called command from the parse result. The comment shows example args and the cast to the expected type. ```csharp var result = Cli.Parse(args); // e.g. args = ["level-1", "level-2"] var called = (Level2SubCliCommand)result.BindCalled(); // binds Level2SubCliCommand ``` -------------------------------- ### Configure basic CliSettings and run command Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-settings.md Configure CliSettings with default exception handler, diagram directive, environment variables directive, and a 5-second process termination timeout, then run the root command with these settings. ```csharp using System.CommandLine; // TryReplaceToken / response file handling come from System.CommandLine var settings = new CliSettings { EnableDefaultExceptionHandler = true, // print unhandled handler exceptions in red EnableDiagramDirective = true, // myapp [diagram] --option-1 value EnableEnvironmentVariablesDirective = true, ProcessTerminationTimeout = TimeSpan.FromSeconds(5), }; return Cli.Run(args, settings); ``` -------------------------------- ### Example: Parse with error handling Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-parser.md Example of parsing arguments and checking for parse errors. The result's ParseResult.Errors collection contains any errors, which are printed to the console. ```csharp var parser = Cli.GetParser(); var result = parser.Parse(new[] { "argument1", "--option-1", "value" }); if (result.ParseResult.Errors.Count > 0) { foreach (var error in result.ParseResult.Errors) Console.WriteLine(error.Message); } ``` -------------------------------- ### Equivalent dotnet commands using response files Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/response-files.md Shows three equivalent command-line invocations: a direct dotnet build command, one using a response file that supplies the entire command, and one using a response file for only the --no-restore option. ```console dotnet build --no-restore --output ./build-output/ dotnet @sample1.rsp dotnet build @sample2.rsp --output ./build-output/ ``` -------------------------------- ### Custom directive example with CliDirective Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/attributes.md Shows a custom directive example. The Debug property is marked with CliDirective and can be invoked as myapp [debug]. Only bool, string, and string[] property types are supported. ```csharp [CliCommand(Description = "Root command with a directive")] public class RootCliCommand { [CliDirective(Description = "Enables debug output")] public bool Debug { get; set; } public void Run() { // Invoke with: myapp [debug] --option-1 value if (Debug) Console.WriteLine("Debug mode is ON"); } } ``` -------------------------------- ### Run app to show help output Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/help-output.md Run the app to display usage help. The first command runs the executable in the project output path; the second runs it from the project directory, using the double hyphen so dotnet run passes the argument to the application. ```console TestApp.exe -? ``` ```console dotnet run -- -? ``` -------------------------------- ### Cli Static Entry Point Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli.md Documentation for the static Cli class entry point, including Run methods, parser creation, and writer properties. ```APIDOC ## [STATIC] Cli.Run ### Description Runs the command-line application with the specified root command type. This is the primary entry point for typical applications. ### Method Run() ### Parameters - **T** (Type) - Required - The root command type that defines the command-line structure. ### Usage Example ```csharp Cli.Run(args); ``` ``` ```APIDOC ## [STATIC] Cli.Run (delegate) ### Description Runs the command-line application using a delegate-based command definition. This is an alternative entry point for simpler scenarios. ### Method Run(Action) ### Parameters - **delegate** (Action) - Required - A delegate that configures the command-line structure. ### Usage Example ```csharp Cli.Run(cli => cli.RootCommand(...)); ``` ``` ```APIDOC ## [STATIC] Cli.GetParser ### Description Creates a CliParser instance for the specified command definition type. This is used internally by Cli.Run methods but can be called directly for advanced scenarios. ### Method GetParser() ### Parameters - **TDefinition** (Type) - Required - The command definition type. ### Returns - **CliParser** - A parser instance configured for the given definition. ``` ```APIDOC ## [STATIC] Cli.Output ### Description Gets the standard output stream wrapped by a CLI writer that provides styled terminal output. ### Property Output (CliWriter) ### Returns - **CliWriter** - A writer for standard output with styling support. ``` ```APIDOC ## [STATIC] Cli.Error ### Description Gets the standard error stream wrapped by a CLI writer, same styling behavior as Output. ### Property Error (CliWriter) ### Returns - **CliWriter** - A writer for standard error with styling support. ``` ```APIDOC ## [STATIC] Cli.Ext ### Description Provides extension methods for Cli, typically used for dependency injection configuration. ### Property Ext (CliExtensions) ### Returns - **CliExtensions** - An instance providing extension methods. ### Usage Example ```csharp Cli.Ext.ConfigureServices(...); ``` ``` -------------------------------- ### Get() / Get(Type definitionType) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-command-builder.md Retrieves the registered CliCommandBuilder for the specified definition type. Throws exceptions if the definition class or its parent lacks the required [CliCommand] attribute, or if no builder is registered. ```APIDOC ## Get() / Get(Type definitionType) ### Description Returns the registered `CliCommandBuilder` for the definition class. ### Method Get ### Signature ```csharp public static CliCommandBuilder Get() public static CliCommandBuilder Get(Type definitionType) ``` ### Parameters - `definitionType` (Type) - Required - The definition type to look up. ### Returns CliCommandBuilder - The registered command builder. ### Exceptions | Exception | Condition | |---|---| | `Exception` | `"The class '' should have [CliCommand] attribute."` — class lacks the attribute. | | `Exception` | `"The parent class '' of nested class '' should have [CliCommand] attribute."` — a nested parent lacks the attribute (checked via `DeclaringType` traversal). | | `Exception` | `"A registered command builder is not found for ''. Please ensure the source generator is running and generating a command builder for your definition class."` | ``` -------------------------------- ### Custom type binding example with Point class Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-binding-context.md Example showing how to use GetArgumentParser to bind a custom type without a Parse method or string constructor. The parser splits a comma-separated string into X and Y coordinates. ```csharp // A custom class with no Parse method / string constructor: public class Point { public int X { get; set; } public int Y { get; set; } } // In a custom command-builder override: Func parser = bindingContext.GetArgumentParser(s => { var parts = s.Split(','); return new Point { X = int.Parse(parts[0]), Y = int.Parse(parts[1]) }; }); ``` -------------------------------- ### HelpBuilder.Default.SubcommandsSection() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the subcommands section writer. ```APIDOC ## [GET] HelpBuilder.Default.SubcommandsSection() ### Description Gets the subcommands section writer. ### Method GET ### Endpoint HelpBuilder.Default.SubcommandsSection() ### Parameters None ### Response #### Success Response - **Func** - The section writer. ``` -------------------------------- ### HelpBuilder.Default.SynopsisSection() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the synopsis section writer. ```APIDOC ## [GET] HelpBuilder.Default.SynopsisSection() ### Description Gets the synopsis section writer. ### Method GET ### Endpoint HelpBuilder.Default.SynopsisSection() ### Parameters None ### Response #### Success Response - **Func** - The section writer. ``` -------------------------------- ### ShowHelp() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-context.md Shows help for the current command by invoking the help option's SynchronousCommandLineAction (CustomHelpAction) with the parse result. Uses the root command's HelpOption, falling back to the current command's, then to a default HelpOption with a CliHelpBuilder(CliTheme.Default). ```APIDOC ## ShowHelp() ### Description Shows help for the current command by invoking the help option's `SynchronousCommandLineAction` (`CustomHelpAction`) with the parse result. Uses the root command's `HelpOption`, falling back to the current command's, then to a default `HelpOption` with a `CliHelpBuilder(CliTheme.Default)`. ### Method ShowHelp() ### Parameters None. ### Returns `void` ### Example ```csharp [CliCommand(Description = "Greet command")] public class GreetCliCommand { [CliOption(Description = "Name to greet")] public string Name { get; set; } = "World"; public void Run(CliContext context) { if (string.IsNullOrEmpty(Name)) { context.ShowHelp(); // print help instead of running return; } Console.WriteLine($"Hello, {Name}!"); } } ``` ``` -------------------------------- ### HelpBuilder.Default.AdditionalArgumentsSection() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the additional arguments section writer. ```APIDOC ## [GET] HelpBuilder.Default.AdditionalArgumentsSection() ### Description Gets the additional arguments section writer. ### Method GET ### Endpoint HelpBuilder.Default.AdditionalArgumentsSection() ### Parameters None ### Response #### Success Response - **Func** - The section writer. ``` -------------------------------- ### HelpBuilder.Default.CommandArgumentsSection() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the command arguments section writer. ```APIDOC ## [GET] HelpBuilder.Default.CommandArgumentsSection() ### Description Gets the command arguments section writer. ### Method GET ### Endpoint HelpBuilder.Default.CommandArgumentsSection() ### Parameters None ### Response #### Success Response - **Func** - The section writer. ``` -------------------------------- ### HelpBuilder.Default.CommandUsageSection() Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the command usage section writer. ```APIDOC ## [GET] HelpBuilder.Default.CommandUsageSection() ### Description Gets the command usage section writer. ### Method GET ### Endpoint HelpBuilder.Default.CommandUsageSection() ### Parameters None ### Response #### Success Response - **Func** - The section writer. ``` -------------------------------- ### HelpBuilder.Default.GetArgumentUsageLabel(Symbol) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the usage label for an argument. ```APIDOC ## [GET] HelpBuilder.Default.GetArgumentUsageLabel(Symbol) ### Description Gets the usage label for an argument. ### Method GET ### Endpoint HelpBuilder.Default.GetArgumentUsageLabel(Symbol) ### Parameters #### Method Parameters - **parameter** (Symbol) - Required - The symbol to get the usage label for. ### Response #### Success Response - **string** - The usage label. ``` -------------------------------- ### Create a CLI app with Cli.Run and a delegate Source: https://github.com/dotmake-build/command-line/blob/main/README.md Create a minimal CLI app by passing a delegate to Cli.Run. Parameters are treated as options by default; mark one with [CliArgument] to make it a positional argument. The delegate can be async and return void or int (or Task/Task when async). ```csharp using System; using DotMake.CommandLine; Cli.Run(([CliArgument]string arg1, bool opt1) => { Console.WriteLine($"Value for {nameof(arg1)} parameter is '{arg1}'"); Console.WriteLine($"Value for {nameof(opt1)} parameter is '{opt1}'"); }); ``` -------------------------------- ### HelpBuilder.Default.GetCommandUsageLabel(Command) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the first-column usage text for a command. ```APIDOC ## [GET] HelpBuilder.Default.GetCommandUsageLabel(Command) ### Description Gets the first-column usage text for a command. ### Method GET ### Endpoint HelpBuilder.Default.GetCommandUsageLabel(Command) ### Parameters #### Method Parameters - **symbol** (Command) - Required - The command to get the usage label for. ### Response #### Success Response - **string** - The usage label. ``` -------------------------------- ### CliDirectiveAttribute Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/attributes.md Documentation for the CliDirectiveAttribute class, including its properties and usage example. ```APIDOC ## CliDirectiveAttribute ### Description Attribute to mark a property or parameter as a directive. Directives are bracket-enclosed tokens (e.g., `myapp [directive:value]`) that appear after the app name but before subcommands/options. Only `bool`, `string`, and `string[]` property types are supported. ### Usage Apply to a property or parameter in a command class. ### Properties - **Name** (string) - Optional - Directive name; auto-generated from the property name (strips `…Directive` suffixes, kebab-case). - **Description** (string) - Optional - Reserved for future use (not displayed). - **Hidden** (bool) - Optional - Reserved for future use. Default: `false`. - **Order** (int) - Optional - Order in help (not displayed currently). Default: `0`. ### Example ```csharp [CliCommand(Description = "Root command with a directive")] public class RootCliCommand { [CliDirective(Description = "Enables debug output")] public bool Debug { get; set; } public void Run() { // Invoke with: myapp [debug] --option-1 value if (Debug) Console.WriteLine("Debug mode is ON"); } } ``` ``` -------------------------------- ### CliArgumentAttribute Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/attributes.md Documentation for the CliArgumentAttribute class, including its properties and a usage example. ```APIDOC ## CliArgumentAttribute ### Description An attribute that marks a property or parameter as a positional argument (e.g., `myapp value`). It configures the argument's name, description, arity, validation, and other behaviors. ### Usage Apply to a property or parameter in a command class. ### Properties - **Name** (string) - Optional - Display name in help; auto-generated from the property name (strips `…Argument` suffixes, kebab-case). - **Description** (string) - Optional - Shown in usage help. - **Hidden** (bool) - Optional - Hide from help. Default: `false`. - **Order** (int) - Optional - Order; affects help and parse order. Default: `0`. - **HelpName** (string) - Optional - Name when displayed in help. - **Required** (bool) - Optional - Same auto-detection rules as `CliOptionAttribute.Required`. - **Arity** (CliArgumentArity) - Optional - `ZeroOrOne` for `bool`, `ZeroOrMore` for collections, `ExactlyOne` otherwise. Default: auto. - **AllowedValues** (string[]) - Optional - Accept only these values (also suggested as completions). - **ValidationRules** (CliValidationRules) - Optional - Bitwise-combinable validation rules. Default: `None`. - **ValidationPattern** (string) - Optional - Regex the value must match. - **ValidationMessage** (string) - Optional - Error message when validation fails. ### Example ```csharp [CliCommand(Description = "Build projects")] public class BuildCliCommand { [CliArgument(Description = "Project path(s)", Arity = CliArgumentArity.ZeroOrMore)] public List Projects { get; set; } = new(); [CliArgument(Description = "Configuration", Order = 1, AllowedValues = new[] { "Debug", "Release" })] public string Configuration { get; set; } = "Debug"; public void Run() { foreach (var project in Projects) Console.WriteLine(project); } } ``` ``` -------------------------------- ### Publish trimmed self-contained deployment with explicit runtime and flags Source: https://github.com/dotmake-build/command-line/blob/main/src/TestApp.NugetAot/README.md Publishes the project with Release configuration, win-x64 runtime, and sets PublishTrimmed and PublishSingleFile to true. The output is generated in the bin\Release\net8.0\win-x64\publish-trimmed folder. ```bash dotnet publish -c Release -r win-x64 -p:PublishTrimmed=true;PublishSingleFile=true ``` -------------------------------- ### HelpBuilder.Default.GetArgumentDescription(Argument) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/help.md Gets the argument's description or an empty string. ```APIDOC ## [GET] HelpBuilder.Default.GetArgumentDescription(Argument) ### Description Gets the argument's description or an empty string. ### Method GET ### Endpoint HelpBuilder.Default.GetArgumentDescription(Argument) ### Parameters #### Method Parameters - **argument** (Argument) - Required - The argument to get the description for. ### Response #### Success Response - **string** - The description or empty string. ``` -------------------------------- ### ShowHierarchy(bool showLevel = false) Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-context.md Prints a tree of all commands starting from the root command (depth-first, tree-drawing characters ├╴, └╴, │), each node styled with the theme's first-column style; level labels styled with the second-column style. ```APIDOC ## ShowHierarchy(bool showLevel = false) ### Description Prints a tree of all commands starting from the root command (depth-first, tree-drawing characters `├╴`, `└╴`, `│`), each node styled with the theme's first-column style; level labels styled with the second-column style. ### Method ShowHierarchy(bool showLevel = false) ### Parameters - **showLevel** (bool) - Optional - Default: `false` - Whether to show level labels next to the tree nodes. ### Returns `void` ### Example ```csharp public void Run(CliContext context) { context.ShowHierarchy(showLevel: true); // myapp (level 0) // ├╴level-1 (level 1) // │ └╴level-2 (level 2) // └╴level-1b (level 1) } ``` ``` -------------------------------- ### Example of mixed nested and external command hierarchy Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/commands.md Example hierarchy showing a mix of nested and external classes. The Parent property can refer to a nested class in another class, but the Children property cannot because having a nested parent is higher priority. A nested child can use Children to refer to non-nested classes. ```text TestApp ├╴external-level-1-with-nested │ └╴level-2 └╴level_1 └╴external_level_2_with_nested └╴level_3 ``` -------------------------------- ### Publish trimmed self-contained deployment Source: https://github.com/dotmake-build/command-line/blob/main/docs/articles/deployment.md Use the first command for a single-target project. If the project has multiple TargetFrameworks, use the second command with the -f net8.0 flag and override TargetFrameworks to net8.0. Output goes to bin\Release\net8.0\win-x64\publish and produces a trimmed, single executable that does not require the .NET runtime. ```console dotnet publish -c Release -r win-x64 -p:PublishTrimmed=true;PublishSingleFile=true ``` ```console dotnet publish -c Release -r win-x64 -f net8.0 -p:PublishTrimmed=true;PublishSingleFile=true;TargetFrameworks=net8.0 ``` -------------------------------- ### Plain output with CliTheme.NoColor Source: https://github.com/dotmake-build/command-line/blob/main/_autodocs/api-reference/cli-theme.md Runs the CLI with the NoColor theme to produce output without any styling or decoration. ```csharp Cli.Run(args, new CliSettings { Theme = CliTheme.NoColor }); ```