Albatross.CommandLine 7.5.8

Prefix Reserved
This package has a SemVer 2.0.0 package version: 7.5.8+c720c5f.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Albatross.CommandLine --version 7.5.8                
NuGet\Install-Package Albatross.CommandLine -Version 7.5.8                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Albatross.CommandLine" Version="7.5.8" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Albatross.CommandLine --version 7.5.8                
#r "nuget: Albatross.CommandLine, 7.5.8"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Albatross.CommandLine as a Cake Addin
#addin nuget:?package=Albatross.CommandLine&version=7.5.8

// Install Albatross.CommandLine as a Cake Tool
#tool nuget:?package=Albatross.CommandLine&version=7.5.8                

Albatross.CommandLine

An integration library that provdes dependency injection, configuration and logging support for System.CommandLine library. It uses Albatross.CommandLine.CodeGen to generate commands and options automatically while giving developers the flexibility to customize and leverage the capability of System.CommandLine library.

Features

Quick Start (Sample Program)

  • Create a .net8 Console program
    • Make sure the Nullable option is enabled for the project.
  • 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 => "Put Your Root Command Description Here";
      	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 services here.
      		services.AddMyProxy();
      	}
      }
    
  • Update the program.cs file
      internal class Program {
      	static Task<int> Main(string[] args) =>
      		new MySetup()
      			.AddCommands()	// this method is generated by CodeGen
      			.CommandBuilder
      			.Build()
      			//.Invoke(args)  // If this call is used, the non async method of the command handler will be invoked
      			.InvokeAsync(args);
      }
    
  • Create a new class file MyCommandHandler.cs with the following code:
      [Verb("my-command", typeof(MyCommandHandler), Description = "My Test Command")]
      public record class MyCommandOptions {
      	public string Name { get; set; } = string.Empty;
      }
      public class MyCommandHandler : ICommandHandler {
      	private readonly ILogger logger;
      	private readonly MyCommandOptions options;
    
      	public MyCommandHandler(ILogger logger, IOptions<MyCommandOptions> options) {
      		this.logger = logger;
      		this.options = options.Value;
      	}
      	// Implement this method to use synchronous invocation
      	public int Invoke(InvocationContext context) => throw new System.NotSupportedException();
      	public Task<int> InvokeAsync(InvocationContext context) {
      		logger.LogInformation("Command {name }is invoked with parameter of {param}", context.ParsedCommandName(), options.Name);
      		return Task.FromResult(0);
      	}
      }
    
  • When the code above is saved, code generator will generate the code below automatically
      // MyCommand
      using System;
      using System.CommandLine;
      using System.IO;
      using System.Threading.Tasks;
    
      #nullable enable
      namespace Sample.CommandLine
      {
      	public sealed partial class MyCommand : Command
      	{
      		public MyCommand() : base("my-command", null)
      		{
      			this.Option_Name = new Option<string>("--name", null)
      			{
      				IsRequired = true
      			};
      			this.AddOption(Option_Name);
      		}
    
      		public Option<string> Option_Name { get; }
      	}
      	public static class RegistrationExtensions
      	{
      		public static IServiceCollection RegisterCommands(this IServiceCollection services)
      		{
      			services.AddKeyedScoped<ICommandHandler, Sample.CommandLine.MyCommandHandler>("my-command");
      			services.AddOptions<MyCommandOptions>().BindCommandLine();
      			return services;
      		}
      	}
      	public static Setup AddCommands(this Setup setup)
      	{
      		setup.AddCommand<MyCommand>();
      		return setup;
      	}
      }
      #nullable disable
    
  • We now have a functional command line program completed with dependency injection, logging and config setup.

Global Options

This global option class is defined as below. Its functionalities are baked into the parent 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

  • 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 the CodeGenExtensions.RegisterCommands() method is not used.
  • 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 injections
  • Override the RootCommandDescription property to create a custom description for the root command.
  • Override the ConfigureBuilder method to customize System.CommandLine to the desired behavior.
  • Override the CreateRootCommand method to change the global options
  • Override 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 of System.CommandLine library.
    • CreateGlobalCommandHandler method can be overwritten to so that a different global handler can be used.
Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
7.8.1 41 12/25/2024
7.8.0 54 12/8/2024
7.6.0 61 11/26/2024
7.5.8 55 11/11/2024
7.5.6 53 11/8/2024
7.5.5 46 11/7/2024