Albatross.CommandLine 7.6.0

Prefix Reserved
This package has a SemVer 2.0.0 package version: 7.6.0+25784b1.
dotnet add package Albatross.CommandLine --version 7.6.0                
NuGet\Install-Package Albatross.CommandLine -Version 7.6.0                
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.6.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Albatross.CommandLine --version 7.6.0                
#r "nuget: Albatross.CommandLine, 7.6.0"                
#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.6.0

// Install Albatross.CommandLine as a Cake Tool
#tool nuget:?package=Albatross.CommandLine&version=7.6.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 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 => "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 TestCommand.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 the CodeGenExtensions.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 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.
  • 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.

    Using the previous TestCommand example, create a partial class for the command and implement interface IRequireInitialization. The partial keyword allows the modification of the generated TestCommand class. Since the class now inherits from IRequireInitialization interface, the Init 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 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.6.0 41 11/26/2024
7.5.8 48 11/11/2024
7.5.6 43 11/8/2024
7.5.5 39 11/7/2024