Albatross.CommandLine
7.8.0
Prefix Reserved
See the version list below for details.
dotnet add package Albatross.CommandLine --version 7.8.0
NuGet\Install-Package Albatross.CommandLine -Version 7.8.0
<PackageReference Include="Albatross.CommandLine" Version="7.8.0" />
paket add Albatross.CommandLine --version 7.8.0
#r "nuget: Albatross.CommandLine, 7.8.0"
// Install Albatross.CommandLine as a Cake Addin #addin nuget:?package=Albatross.CommandLine&version=7.8.0 // Install Albatross.CommandLine as a Cake Tool #tool nuget:?package=Albatross.CommandLine&version=7.8.0
Albatross.CommandLine
An integration library that simplifies the creation of console program using the System.CommandLine library. It provdes code generation, dependency injection, configuration and logging support. It uses Albatross.CommandLine.CodeGen to generate commands and options automatically while giving developers the flexibility to fully leverage the capability of System.CommandLine library.
Features
- Quick setup with dependency injection enabled by Code Generator.
- Logging integration with Serilog provided by Albatross.Logging.
- Easy configuration setup provided by Albatross.Config.
Related Articles
- Code Generator
- Conventions
- Command Options
- Sub Commands
- How to Create Mutually Exclusive Options
- Global Options
- Error Handling
- Customizations
Quick Start (Sample Program)
- Create a .net8 Console program
- Make sure the
Nullable
option is enabled for the project.
- Make sure the
- Reference Albatross.CommandLine from nuget. Albatross.CommandLine.CodeGen should be referenced automatically as a dev dependency.
- Create a class MySetup.cs that inherits base class Albatross.CommandLine.Setup
public class MySetup : Setup { protected override string RootCommandDescription => "This a sample command"; public override void RegisterServices(InvocationContext context, IConfiguration configuration, EnvironmentSetting envSetting, IServiceCollection services) { base.RegisterServices(context, configuration, envSetting, services); // RegisterCommands method is generated by codegen services.RegisterCommands(); // register your dependencies here services.AddSingleton<IMyService, MyService>(); } }
- Update the program.cs file
internal class Program { static Task<int> Main(string[] args) => new MySetup() // this method is generated by CodeGen .AddCommands() .CommandBuilder .Build() // If this call is used, the non async method of the command handler will be invoked //.Invoke(args) .InvokeAsync(args); }
- Create a new class file TestCommandHandler.cs with the following code:
[Verb("test", typeof(TestCommandHandler), Description = "My Test Command")] public record class TestCommandOptions { // Name is a required option by default since the property is not nullable public string Name { get; set; } = string.Empty; // Description is optional since the property is nullable public string? Description { get; set; } // The OptionAttribute can be used the change the default requirement behavior. In this case, changing the Id option to be optional [Option(Required = false)] public int Id { get; set; } } public class TestCommandHandler : ICommandHandler { private readonly ILogger logger; private readonly TestCommandOptions options; public TestCommandHandler(ILogger logger, IOptions<TestCommandOptions> options) { this.logger = logger; this.options = options.Value; } public int Invoke(InvocationContext context) { context.Console.WriteLine(context.ParseResult.Diagram()); return 0; } public Task<int> InvokeAsync(InvocationContext context) { return Task.FromResult(Invoke(context)); } }
- When the code above is saved, code generator will generate the code below automatically
// ********** TestCommand.cs ********** // using System; using System.CommandLine; using System.IO; using System.Threading.Tasks; #nullable enable namespace Sample.CommandLine { public sealed partial class TestCommand : Command { public TestCommand() : base("test", "My Test Command") { this.Option_Name = new Option<string>("--name", null) { IsRequired = true }; this.AddOption(Option_Name); this.Option_Description = new Option<string?>("--description", null); this.AddOption(Option_Description); this.Option_Id = new Option<int>("--id", null); this.AddOption(Option_Id); } public Option<string> Option_Name { get; } public Option<string?> Option_Description { get; } public Option<int> Option_Id { get; } } } #nullable disable
- The following command creation and service registration code are also generated automatically.
// ********** CodeGenExtensions.cs ********** // #nullable enable namespace Sample.CommandLine { public static class CodeGenExtensions { public static IServiceCollection RegisterCommands(this IServiceCollection services) { services.AddKeyedScoped<ICommandHandler, Sample.CommandLine.TestCommandHandler>("test"); services.AddOptions<TestCommandOptions>().BindCommandLine(); return services; } public static Setup AddCommands(this Setup setup) { var dict = new Dictionary<string, Command>(); dict.Add(string.Empty, setup.RootCommand); dict.AddCommand<TestCommand>("test"); return setup; } } } #nullable disable
- We now have a functional command line program completed with dependency injection, logging and config setup. Note that the generated code are saved in a file called
albatross-commandline-codegen.debug.txt
for troubleshooting. Currently there is no option to disable it. It should be ignored by source control.
Global Options
This global option class is defined as below. Its functionalities are baked into the global command handler and available for all commands.
public record class GlobalOptions {
// default is Error
public LogLevel? Verbosity { get; set; }
// when true, log the duration of command execution in milliseconds
public bool Benchmark { get; set; }
// when true, show the full stack when there is an exception
public bool ShowStack { get; set; }
}
Error Handling and Trouble Shooting
- Unhandled command handler exception will be caught and an error code of
10000
will be returned. The exception message will be logged as error. If the--show-stack
option is set, the full code stack will be logged instead. - An error code of
9999
will be returned if there is an issue constructing the command handler instance. It could happen when the dependency is not property configured. - An error code of
9998
will be returned if the command handler is not registered. This could happen if theCodeGenExtensions.RegisterCommands()
method is not called. - If none of the defined commands shows up,
CodeGenExtensions.AddCommands()
method is not invoked.
Customization
Setup has a few methods that can be overwritten to change the behavior of the program
Override the
RegisterServices
method to setup dependency injectionsOverride the
RootCommandDescription
property to create a custom description for the root command.Override the
ConfigureBuilder
method to customizeSystem.CommandLine
to the desired behavior.Override the
CreateRootCommand
method to change the global optionsOverride the
CreateGlobalCommandHandler
method to use your own global command handler.- Albatross.CommandLine uses an instance of GlobalCommandHandler for all commands. Its job is to invoke the specific sub command handler, error handling and implementation of global options. The
GlobalCommandHandler
class bypasses the error handling mechanism ofSystem.CommandLine
library. CreateGlobalCommandHandler
method can be overwritten to so that a different global handler can be used.
- Albatross.CommandLine uses an instance of GlobalCommandHandler for all commands. Its job is to invoke the specific sub command handler, error handling and implementation of global options. The
Albatross.CommandLine
library does not prevent users from using a manually created command and its handler. It should just work after the command is added to the root command.Generated Command Customization - It might be easier to modify a generated command instead. example
Using the previous
TestCommand
example, create a partial class for the command and implement interfaceIRequireInitialization
. The partial keyword allows the modification of the generatedTestCommand
class. Since the class now inherits fromIRequireInitialization
interface, theInit
method will be invoked when the command is constructed. This is a good place to add validators or other customizations. In the sample code below, a custom validator is added.public partial class TestCommand : IRequireInitialization { public void Init() { AddValidator(commandResult => { // add your custom validation here }); } }
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.1 is compatible. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- Albatross.CommandLine.CodeGen (>= 7.8.0)
- Albatross.Config (>= 7.5.7)
- Albatross.Logging (>= 8.0.0)
- Albatross.Text (>= 7.5.7)
- Microsoft.Extensions.DependencyInjection (>= 8.0.1)
- Microsoft.Extensions.Hosting (>= 8.0.1)
- Spectre.Console (>= 0.49.1)
- System.CommandLine (>= 2.0.0-beta4.22272.1)
- System.CommandLine.Hosting (>= 0.4.0-alpha.22272.1)
- System.CommandLine.NamingConventionBinder (>= 2.0.0-beta4.22272.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.