Giter Site home page Giter Site logo

clifx's Introduction

CliFx

Status Made in Ukraine Build Coverage Version Downloads Discord Fuck Russia

Development of this project is entirely funded by the community. Consider donating to support!

Icon

CliFx is a simple to use, yet powerful framework for building command-line applications. Its 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.

Terms of use[?]

By 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:

  • You condemn Russia and its military aggression against Ukraine
  • You recognize that Russia is an occupant that unlawfully invaded a sovereign state
  • You support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas
  • You reject false narratives perpetuated by Russian state propaganda

To learn more about the war and how you can help, click here. Glory to Ukraine! πŸ‡ΊπŸ‡¦

Install

  • πŸ“¦ NuGet: dotnet add package CliFx

Features

  • Complete application framework, not just an argument parser
  • Minimum boilerplate and easy to get started
  • Class-first configuration via attributes
  • Comprehensive auto-generated help text
  • Support for deeply nested command hierarchies
  • Graceful cancellation via interrupt signals
  • Support for reading and writing binary data
  • Testable console interaction layer
  • Built-in analyzers to catch configuration issues
  • Targets .NET Standard 2.0+
  • No external dependencies

Screenshots

help screen

Usage

Quick overview

To turn your program into a command-line interface, modify the Main() method so that it delegates the execution to an instance of CliApplication. You can use CliApplicationBuilder to simplify the process of creating and configuring an application:

using CliFx;

public static class Program
{
    public static async Task<int> Main() =>
        await new CliApplicationBuilder()
            .AddCommandsFromThisAssembly()
            .Build()
            .RunAsync();
}

Warning: Ensure that your Main() method returns the integer exit code provided by CliApplication.RunAsync(), as shown in the above example. Exit code is used to communicate execution result to the parent process, so it's important that your program propagates it.

Note: When calling CliApplication.RunAsync(), CliFx resolves command-line arguments and environment variables from Environment.GetCommandLineArgs() and Environment.GetEnvironmentVariables() respectively. You can also provide them manually using one of the alternative overloads.

The code above uses AddCommandsFromThisAssembly() to detect command types defined within the current project and register them on the application. Commands are independent entry points, through which the user can interact with your program.

To define a command, create a class that implements the ICommand interface and annotate it with the [Command] attribute:

using CliFx;
using CliFx.Attributes;

[Command(Description = "Calculates the logarithm of a value.")]
public class LogCommand : ICommand
{
    // Order: 0
    [CommandParameter(0, Description = "Value whose logarithm is to be found.")]
    public required double Value { get; init; }

    // Name: --base
    // Short name: -b
    [CommandOption("base", 'b', Description = "Logarithm base.")]
    public double Base { get; init; } = 10;

    public ValueTask ExecuteAsync(IConsole console)
    {
        var result = Math.Log(Value, Base);
        console.Output.WriteLine(result);

        // If the execution is not meant to be asynchronous,
        // return an empty task at the end of the method.
        return default;
    }
}

In order to implement ICommand, the class needs to define an ExecuteAsync(...) method. This is the method that gets called by the framework when the user decides to execute the command.

As the only parameter, this method takes an instance of IConsole, which is an abstraction around the system console. Use this abstraction in place of System.Console whenever you need to write output, read input, or otherwise interact with the console.

In most cases, you will also want to define input bindings, which are properties annotated by the [CommandParameter] and [CommandOption] attributes. These bindings provide a way to map command-line arguments into structured input data that can be used by the command.

The 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. In order to execute this command, at minimum, the user needs to provide the input value:

$ dotnet myapp.dll 10000

4

They can also pass the -b|--base option to override the default logarithm base of 10:

$ dotnet myapp.dll 729 -b 3

6

In case the user forgets to specify the required value parameter, the application will instead exit with an error:

$ dotnet myapp.dll -b 10

Missing required parameter(s):
<value>

Out 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:

$ dotnet myapp.dll --help

MyApp v1.0

USAGE
  dotnet myapp.dll <value> [options]

DESCRIPTION
  Calculates the logarithm of a value.

PARAMETERS
* value             Value whose logarithm is to be found.

OPTIONS
  -b|--base         Logarithm base. Default: "10".
  -h|--help         Shows help text.
  --version         Shows version information.

Argument syntax

This library employs a variation of the POSIX argument syntax, which is used in most modern command-line tools. Here are some examples of how it works:

  • myapp --foo bar sets option "foo" to value "bar"
  • myapp -f bar sets option 'f' to value "bar"
  • myapp --switch sets option "switch" without value
  • myapp -s sets option 's' without value
  • myapp -abc sets options 'a', 'b' and 'c' without value
  • myapp -xqf bar sets options 'x' and 'q' without value, and option 'f' to value "bar"
  • myapp -i file1.txt file2.txt sets option 'i' to a sequence of values "file1.txt" and "file2.txt"
  • myapp -i file1.txt -i file2.txt sets option 'i' to a sequence of values "file1.txt" and "file2.txt"
  • myapp cmd abc -o routes to command cmd (assuming it's a command) with parameter abc and sets option 'o' without value

Additionally, argument parsing in CliFx aims to be as deterministic as possible, ideally yielding the same result regardless of the application configuration. In 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.

The parser's context-free nature has several implications on how it consumes arguments. For 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. Similarly, 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".

These rules also make the order of arguments important β€” command-line string is expected to follow this pattern:

$ myapp [...directives] [command] [...parameters] [...options]

Parameters and options

CliFx supports two types of argument bindings: parameters and options. Parameters are bound from the command-line arguments based on the order they appear in, while options are bound by their name.

Besides that, they also differ in the following ways:

  • Parameters are required by default, while options are not.

    • 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):

      // Any option can be required or optional without restrictions
      [CommandOption("foo")]
      public required string RequiredOption { get; init; }
    • To make a parameter optional, you can set IsRequired = false, but only the last parameter (by order) can be configured in such way:

      // Only the last parameter can be optional
      [CommandParameter(0, IsRequired = false)]
      public string? OptionalParameter { get; init; }
  • Parameters are primarily used for scalar (non-enumerable) properties, while options can be used for both scalar and non-scalar properties.

    • You can bind an option to a property of a non-scalar type, such as IReadOnlyList<T>:

      // Any option can be non-scalar
      [CommandOption("foo")]
      public required IReadOnlyList<string> NonScalarOption { get; init; }
    • You can bind a parameter to a non-scalar property, but only if it's the last parameter in the command:

      // Only the last parameter can be non-scalar
      [CommandParameter(0)]
      public required IReadOnlyList<string> NonScalarParameter { get; init; }
  • Options can rely on an environment variable for fallback, while parameters cannot:

    // If the value is not provided directly, it will be read
    // from the environment variable instead.
    // This works for both scalar and non-scalar properties.
    [CommandOption("foo", EnvironmentVariable = "ENV_FOO")]
    public required string OptionWithFallback { get; init; }

Note: CliFx has a set of built-in analyzers that detect common errors in command definitions. Your code will not compile if a command contains duplicate options, overlapping parameters, or otherwise invalid configuration.

Value conversion

Parameters and options can be bound to properties with the following underlying types:

  • Basic types
    • Primitive types (int, bool, double, ulong, char, etc.)
    • Date and time types (DateTime, DateTimeOffset, TimeSpan)
    • Enum types (converted from either name or numeric value)
  • String-initializable types
    • Types with a constructor accepting a string (FileInfo, DirectoryInfo, etc.)
    • Types with a static Parse(...) method accepting a string and optionally a IFormatProvider (Guid, BigInteger, etc.)
  • Nullable versions of all above types (decimal?, TimeSpan?, etc.)
  • Any other type if a custom converter is specified
  • Collections of all above types
    • Array types (T[])
    • Types that are assignable from arrays (IReadOnlyList<T>, ICollection<T>, etc.)
    • Types with a constructor accepting an array (List<T>, HashSet<T>, etc.)

Non-scalar parameters and options

Here's an example of a command with an array-backed parameter:

[Command]
public class FileSizeCalculatorCommand : ICommand
{
    // FileInfo is string-initializable and IReadOnlyList<T> can be assigned from an array,
    // so the value of this property can be mapped from a sequence of arguments.
    [CommandParameter(0)]
    public required IReadOnlyList<FileInfo> Files { get; init; }

    public ValueTask ExecuteAsync(IConsole console)
    {
        var totalSize = Files.Sum(f => f.Length);
        console.Output.WriteLine($"Total file size: {totalSize} bytes");

        return default;
    }
}
$ dotnet myapp.dll file1.bin file2.exe

Total file size: 186368 bytes

Custom conversion

To create a custom converter for a parameter or an option, define a class that inherits from BindingConverter<T> and specify it in the attribute:

// Maps 2D vectors from AxB notation
public class VectorConverter : BindingConverter<Vector2>
{
    public override Vector2 Convert(string? rawValue)
    {
        if (string.IsNullOrWhiteSpace(rawValue))
            return default;

        var components = rawValue.Split('x', 'X', ';');
        var x = int.Parse(components[0], CultureInfo.InvariantCulture);
        var y = int.Parse(components[1], CultureInfo.InvariantCulture);

        return new Vector2(x, y);
    }
}

[Command]
public class SurfaceCalculatorCommand : ICommand
{
    // Custom converter is used to map raw argument values
    [CommandParameter(0, Converter = typeof(VectorConverter))]
    public required Vector2 PointA { get; init; }

    [CommandParameter(1, Converter = typeof(VectorConverter))]
    public required Vector2 PointB { get; init; }

    [CommandParameter(2, Converter = typeof(VectorConverter))]
    public required Vector2 PointC { get; init; }

    public ValueTask ExecuteAsync(IConsole console)
    {
        var a = (PointB - PointA).Length();
        var b = (PointC - PointB).Length();
        var c = (PointA - PointC).Length();

        var p = (a + b + c) / 2;
        var surface = Math.Sqrt(p * (p - a) * (p - b) * (p - c));

        console.Output.WriteLine($"Triangle surface area: {surface}");

        return default;
    }
}
$ dotnet myapp.dll 0x0 0x10 10x0

Triangle surface area: 50

Multiple commands

In order to facilitate a variety of different workflows, command-line applications may provide the user with more than just a single command. Complex applications may also nest commands underneath each other, employing a multi-level hierarchical structure.

With CliFx, this is achieved by simply giving each command a unique name through the [Command] attribute. Commands that have common name segments are considered to be hierarchically related, which affects how they're listed in the help text.

// Default command, i.e. command without a name
[Command]
public class DefaultCommand : ICommand
{
    // ...
}

// Child of default command
[Command("cmd1")]
public class FirstCommand : ICommand
{
    // ...
}

// Child of default command
[Command("cmd2")]
public class SecondCommand : ICommand
{
    // ...
}

// Child of FirstCommand
[Command("cmd1 sub")]
public class SubCommand : ICommand
{
    // ...
}

Once configured, the user can execute a specific command by prepending its name to the passed arguments. For example, running dotnet myapp.dll cmd1 arg1 -p 42 will execute FirstCommand in the above example.

The user can also find the list of all available top-level commands in the help text:

$ dotnet myapp.dll --help

MyApp v1.0

USAGE
  dotnet myapp.dll [options]
  dotnet myapp.dll [command] [...]

OPTIONS
  -h|--help         Shows help text.
  --version         Shows version information.

COMMANDS
  cmd1              Subcommands: cmd1 sub.
  cmd2

You can run `dotnet myapp.dll [command] --help` to show help on a specific command.

To 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:

$ dotnet myapp.dll cmd1 --help

USAGE
  dotnet myapp.dll cmd1 [options]
  dotnet myapp.dll cmd1 [command] [...]

OPTIONS
  -h|--help         Shows help text.

COMMANDS
  sub

You can run `dotnet myapp.dll cmd1 [command] --help` to show help on a specific command.

Note: Defining the default (unnamed) command is not required. If it's absent, running the application without specifying a command will just show the root-level help text.

Reporting errors

Commands in CliFx do not directly return exit codes, but instead communicate execution errors via CommandException. This 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:

[Command]
public class DivideCommand : ICommand
{
    [CommandOption("dividend")]
    public required double Dividend { get; init; }

    [CommandOption("divisor")]
    public required double Divisor { get; init; }

    public ValueTask ExecuteAsync(IConsole console)
    {
        if (Math.Abs(Divisor) < double.Epsilon)
        {
            // This will print the error and set exit code to 133
            throw new CommandException("Division by zero is not supported.", 133);
        }

        var result = Dividend / Divisor;
        console.Output.WriteLine(result);

        return default;
    }
}
$ dotnet myapp.dll --dividend 10 --divisor 0

Division by zero is not supported.

$ echo $?

133

Warning: 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. To avoid unexpected results, use numbers between 1 and 255 for exit codes that indicate failure.

Graceful cancellation

Console applications support the concept of interrupt signals, which can be issued by the user to abort the currently ongoing operation. If your command performs critical work, you can intercept these signals to handle cancellation requests in a graceful way.

In order to make the command cancellation-aware, call console.RegisterCancellationHandler() to register the signal handler and obtain the corresponding CancellationToken. Once 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.

[Command]
public class CancellableCommand : ICommand
{
    private async ValueTask DoSomethingAsync(CancellationToken cancellation)
    {
        await Task.Delay(TimeSpan.FromMinutes(10), cancellation);
    }

    public async ValueTask ExecuteAsync(IConsole console)
    {
        // Make the command cancellation-aware
        var cancellation = console.RegisterCancellationHandler();

        // Execute some long-running cancellable operation
        await DoSomethingAsync(cancellation);

        console.Output.WriteLine("Done.");
    }
}

Warning: Cancellation handler is only respected when the user sends the interrupt signal for the first time. If the user decides to issue the signal again, the application will be forcefully terminated without triggering the cancellation token.

Type activation

Because CliFx takes responsibility for the application's entire lifecycle, it needs to be capable of instantiating various user-defined types at run-time. To facilitate that, it uses an interface called ITypeActivator that determines how to create a new instance of a given type.

The default implementation of ITypeActivator only supports types that have public parameterless constructors, which is sufficient for the majority of scenarios. However, in some cases you may also want to define a custom initializer, for example when integrating with an external dependency container.

To do that, pass a custom ITypeActivator or a factory delegate to the UseTypeActivator(...) method when building the application:

public static class Program
{
    public static async Task<int> Main() =>
        await new CliApplicationBuilder()
            .AddCommandsFromThisAssembly()
            .UseTypeActivator(type =>
            {
                var instance = MyTypeFactory.Create(type);
                return instance;
            })
            .Build()
            .RunAsync();
}

This method also supports IServiceProvider through various overloads, which allows you to directly integrate dependency containers that implement this interface. For example, this is how to configure your application to use Microsoft.Extensions.DependencyInjection as the type activator in CliFx:

public static class Program
{
    public static async Task<int> Main() =>
        await new CliApplicationBuilder()
            .AddCommandsFromThisAssembly()
            .UseTypeActivator(commandTypes =>
            {
                var services = new ServiceCollection();

                // Register services
                services.AddSingleton<MyService>();

                // Register commands
                foreach (var commandType in commandTypes)
                    services.AddTransient(commandType);

                return services.BuildServiceProvider();
            })
            .Build()
            .RunAsync();
}

Testing

Thanks to the IConsole abstraction, CliFx commands can be easily tested in isolation. While 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.

For example, imagine you have the following command:

[Command]
public class ConcatCommand : ICommand
{
    [CommandOption("left")]
    public string Left { get; init; } = "Hello";

    [CommandOption("right")]
    public string Right { get; init; } = "world";

    public ValueTask ExecuteAsync(IConsole console)
    {
        console.Output.Write(Left);
        console.Output.Write(' ');
        console.Output.Write(Right);

        return default;
    }
}

To test it, you can instantiate the command in code with the required values, and then pass an instance of FakeInMemoryConsole to ExecuteAsync(...):

// Integration test at the command level
[Test]
public async Task ConcatCommand_executes_successfully()
{
    // Arrange
    using var console = new FakeInMemoryConsole();

    var command = new ConcatCommand
    {
        Left = "foo",
        Right = "bar"
    };

    // Act
    await command.ExecuteAsync(console);

    // Assert
    var stdOut = console.ReadOutputString();
    Assert.That(stdOut, Is.EqualTo("foo bar"));
}

Similarly, you can also test your command at a higher level like so:

// End-to-end test at the application level
[Test]
public async Task ConcatCommand_executes_successfully()
{
    // Arrange
    using var console = new FakeInMemoryConsole();

    var app = new CliApplicationBuilder()
        .AddCommand<ConcatCommand>()
        .UseConsole(console)
        .Build();

    var args = new[]
    {
        "--left", "foo",
        "--right", "bar"
    };

    var envVars = new Dictionary<string, string>();

    // Act
    await app.RunAsync(args, envVars);

    // Assert
    var stdOut = console.ReadOutputString();
    Assert.That(stdOut, Is.EqualTo("foo bar"));
}

Debug and preview mode

When troubleshooting issues, you may find it useful to run your app in debug or preview mode. To do that, pass the corresponding directive before any other command-line arguments.

In order to run the application in debug mode, use the [debug] directive. This will cause the program to launch in a suspended state, waiting for the debugger to attach to the current process:

$ dotnet myapp.dll [debug] cmd -o

Attach debugger to PID 3148 to continue.

To run the application in preview mode, use the [preview] directive. This will short-circuit the execution and instead print the consumed command-line arguments as they were parsed, along with resolved environment variables:

$ dotnet myapp.dll [preview] cmd arg1 arg2 -o foo --option bar1 bar2

Command-line:
  cmd <arg1> <arg2> [-o foo] [--option bar1 bar2]

Environment:
  FOO="123"
  BAR="xyz"

You can also disallow these directives, e.g. when running in production, by calling AllowDebugMode(...) and AllowPreviewMode(...) methods on CliApplicationBuilder:

var app = new CliApplicationBuilder()
    .AddCommandsFromThisAssembly()
    .AllowDebugMode(true) // allow debug mode
    .AllowPreviewMode(false) // disallow preview mode
    .Build();

Etymology

CliFx is made out of "Cli" for "Command-line Interface" and "Fx" for "Framework". It's pronounced as "cliff ex".

clifx's People

Contributors

89netram avatar adustyoldmuffin avatar alexrosenfeld10 avatar alirezanet avatar blackgad avatar cartblanche avatar dgarcia202 avatar domn1995 avatar es-rene99 avatar federico-paolillo avatar inech avatar moophic avatar nikiforovall avatar oshustov avatar rcdailey avatar ron-myers avatar tagc avatar thorhj avatar tyrrrz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clifx's Issues

Subcommands

Allow specifying command "routes", e.g. app.exe create file --name newfile.txt and app.exe create directory --name newdir.

After upgrading from 0.0.8 to 1.0.0, Dependency injection management using Autofac failed

using Autofac;

            var builder = new ContainerBuilder();
            builder.RegisterAssemblyModules(typeof(Logic.Global).Assembly);

            builder.RegisterType<SerialCliCommand>().Named<ICommand>("serial").SingleInstance();
            builder.RegisterType<CareConfigCliCommand>().Named<ICommand>("cc").SingleInstance();
            builder.RegisterType<CareCliCommand>().Named<ICommand>("ci").SingleInstance();
            builder.RegisterType<DataCommand>().Named<ICommand>("d").SingleInstance();

            var container = builder.Build();

            await new CliApplicationBuilder()
                .AddCommandsFromThisAssembly()
                .UseTypeActivator(type => container.ResolveNamed<ICommand>(type.Name))
                .Build()
                .RunAsync(args);

Environment variables

Extend CommandOptionAttribute by adding EnvironmentVariableName. If the corresponding environment variable is set, the option property will take on its value, but only if the corresponding command line argument was not set. In other words, command line argument > environment variable > default value.

Force the display of a command's help text from ExecuteAsync?

First of all, I love project! Here's the use case I'm trying figure out:

I have a pretty nested CLI app where some commands don't actually do anything, but rather just help organize the app. Example:

myapp
|_ sub1
   |_ sub-sub1

In this example, command sub1 doesn't do anything except organize the structure of the commands. As such, in the ICommand.ExecuteAsync(IConsole) implementation, I'm simply returning default. When running the app in the following manner myapp sub, it simply executes then exits without doing anything. My intended behavior, however, is for it to print its help text instead.

Is it possible to do this currently? Or is there a better way to implement this pattern?

Thanks, and again, I love the library!!! And I hope you enjoy the three coffees I bought you @Tyrrrz :)

Add support for getting the input command

Need to add support for getting original command entered at start. I've encountered a scenario where I needed to store the original command, although could not find anything for it. If there is, can you point me towards it?

Tests sometimes throw ArgumentOutOfRangeException on Windows CI

See the following test run where Command may throw a specialized exception which shows only the help text FT throws an ArgumentOutOfRangeException:
https://github.com/Tyrrrz/CliFx/pull/54/checks?check_run_id=676614514

Then another run with no changes and it works fine:
https://github.com/Tyrrrz/CliFx/pull/54/checks?check_run_id=676630738

Not sure there's anything we can do about since it seems to be happening in the underlying Windows API, but worth documenting anyway.

Add cursor position control to IConsole interface

Description

Sometimes you wish to overwrite previously entered output, e.g. when creating a loading bar or a spinner. This is not possible through the recommended IConsole instance, as it does not define contracts for controlling the cursor position.

Suggested solution

Add the following signatures to IConsole:

CursorLeft { get; set; }
CursorTop { get; set; }
CursorVisible { get; set; }
CursorSize { get; set; }
SetCursorPosition(int, int)

I suspect these have been left out of the interface because of the VirtualConsole implementation. Alternatively, a spinner class could be added to the framework similar to ProgressReporter.

How to add logging to services

Hi!

I like this library, it looks clean and well written.
I only find the progress reporting a bit lacking because i'd like to add what im doing or processing when i report progress (e.g. 50% removing file: c:/somefolder/somefile.txt).

but to the core of my question;

I have SomeService which is injected to MyCmd, now i'd like to do some logging from out of my service. In asp.net core i inject a logger factory for this. However i'm uncertain how to go about this when using this fx. Any thoughts?

edit; playing around with trying to get IConsole from CliApplication into the container somehow.

Create abstractions package

Create a package with the interfaces (such as IConsole) to allow for custom implementations without importing the whole library.

Use Case

For referencing the abstractions package in a common library that may be used across CLI, UI, Web applications. For example, a Logger that can take an IConsole as a parameter and wrap the output. Allowing for methods like Error(), Information() etc, that can add extra information (like timestamps, colors, etc).

Suggested Implementation

Move the following interfaces to the package

  • IConsole
  • ICommand
  • ICliApplication
  • ICliApplicationBuilder
  • ICommandFactory

It may be helpful to include all of the core interfaces in here, however I leave that up to you.

Support version and help commands

Many CLI tools have built-in version and help commands. For example:

>git version
git version 2.9.2.windows1

>git help
usage: git [...]
...
  • Are we interested in supporting this in CliFx?
  • Also, if supporting help as a builtin command, do we want it only for the root of the app or to all subcommands? I propose all subcommands.
  • For the builtin 'version` command, I think it would only make sense to be built in to the root of the app.

Customizable option format/grammar

Currently, CliFx only accepts options in a form of --some-argument value. It would be nice if you could customize it to accept different characters in place of whitespace, e.g. --some-argument=value. The next step would also be to make the entire grammar completely customizable so the user could use different styles/standards, e.g. /some-argument:value.

Custom value conversion

Add some sort of functionality that lets users specify custom converter for command parameters/options.

Needs to work well with both scalar and non-scalar (i.e. array) arguments.

Thinking about using attributes for this, but maybe there are better options.

Allow for minimum number of items in array-backed parameters

When I have a parameter like this:

[CommandParameter(0)]
public FileInfo File { get; set; }

And I don't pass in a file, the program display the help message. However, if I make that a list:

[CommandParameter(0)]
public IReadOnlyList<FileInfo> Files { get; set; }

And don't pass in any files, the command runs. It would be really helpful to be able to specify that the parameter needs to have at least one file.

Anonymous options

...aka options that don't have a name.

Allow doing something like app command <option> or even app command <option> subcommand. Currently this is not possible because <option> will be parsed as part of the command name.

Also, what do we do in case of conflicts? E.g. app command <option> where <option> matches the name of one of the subcommands.

Some inspiration can be drawn here: http://docopt.org/

Allow scalar option/parameter types be constructed with arrays of strings

Proposal

Allow the supported types of options/parameters be constructed with enumerables of strings, not just raw strings. This is already essentially supported, but with a "wart" in a form of a requirement to implement a dummy interface (see below). For this reason, the proposal concerns only adding the support for new(ICollectionType<string> strings) signature.

Motivation

To provide a better user experience, I have been using arrays of strings instead of raw strings to not have to use quotes when specifying argument values:

[CommandParameter(0)]
string[] BookName { get; set; }
//add book The Book With A Long Title 
//instead of
//add book "The Book With A Long Title"

I decided to take advantage of CliFX's default handling of invalid/missing arguments, so I created a strong type for BookName to replace string[]:

public class Name
{
   public Name(string[] strings) => Value = string.Join(' ', strings);
   public string Value { get; set; }
}

This, unfortunately, does not work in the current version (in the README file, there is a mention of types with constructors of supported types also being supported, which lead to me to believe this was possible in the first place, but this could be attributed to me misinterpreting the documentation, since this point is under "Supports collection types" header, which logically excludes scalars). What does work (as expected), however, is the following workaround:

public class Name : IEnumerable
{
   public Name(string[] strings) => Value = string.Join(' ', strings);
   public string Value { get; set; }
   IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException();
}

Thus I decided to file this issue to see if there would be a possibility of adding "full" support for this pattern.

Implementation

As far as I understand, this would involve refactoring the logic here to support the notion of an enumerable type being not just a type with enumerableUnderlyingType == null, but also one with the appropriate constructor. A bigger refactoring could be considered, and the notion of "fake" enumerable types could be introduced, but the determination of need for that requires a deeper understanding of the codebase, which I do not (yet) have. It would seem reasonable to me to assume that the fact that the value is a "real" enumerable is of questionable relevance, since that information could only be useful if there is a need to actually call the iterator methods, which the library currently does not do, at least according to the GitHub search for GetEnumerator.

Custom value validation

Currently, the only way to validate a value is to check it in ExecuteAsync and throw CommandExecution if it's invalid. This can be made to look nicer with tools like FluentValidation but it's still quite verbose and cumbersome.

One option is to use the standard ValidationAttribute but it has some bloat.

Add support for positional arguments

Commands may have an argument that is always required and makes sense semantically without an option flag. E.g.:

git checkout <ref>

Positional arguments are not supported, so the above would need to be invoked like this:

git checkout --ref <ref>

Options groups

Specify a group on an option. Options from the same group can/cannot be used simultaneously.

Show default values of non-required options in help

Suggested approach:

  • Resolve target command
  • Instantiate the command but don't fill the values
  • Get the values of the properties on the freshly-instantiated command, filter out those that are default and show them in help text

Multiple characters for short name

From using other CLI tools it's common to have multiple character short names to avoid clashing of commands I.E. --save, -s --saveFile, -sf

Is it possible that support for this could be added?

Option validation attributes

Introduce a set of attributes that dictate the range of valid values an option can take.
Examples: StringLength, RegularExpression, Range.

Order changes parser behavior?

For some reason the first sample below works, but the second does not. For some reason the ordening of the options change the behaviour of the parser (or i'm missing something).

1>  "C:\Repos\HMI4\Tools\HmiPluginDllManager\bin\Debug\netcoreapp3.1\HmiPluginDllManager.exe" [preview] CpyPluginDlls -p "WebHmi.HmiPlugins" -c "Debug" -o "C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug\"
Parser preview:
CpyPluginDlls [-p WebHmi.HmiPlugins] [-c Debug] [-o C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug"] 
"C:\Repos\HMI4\Tools\HmiPluginDllManager\bin\Debug\netcoreapp3.1\HmiPluginDllManager.exe" [preview] CpyPluginDlls -p "WebHmi.HmiPlugins" -o "C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug\" -c "Debug"
Parser preview:
CpyPluginDlls [-p WebHmi.HmiPlugins] [-o 
 C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug" -c Debug"] 

Add option for adding multiple items when we specify List<object>?

In my api I can use something like api/projects?statuses=1,2,3 it would be perfect also use this feature.

Example code:

    ```
    Another command options (working fine)

    [CommandOption("statuses", IsRequired = false)]
    public List<ProjectStatus?> Statuses { get; set; }
    
    public async ValueTask ExecuteAsync(IConsole console)
    {
        await console.Output.WriteLineAsync("Getting projects as yaml");
        var json = await Helpers.Transformer($"{TaikunURLs.getProjects}?statuses={Statuses}");
        var swaggerDocument = Helpers.ConvertJTokenToObject(JsonConvert.DeserializeObject<JToken>(json));

        var serializer = new YamlDotNet.Serialization.Serializer();

        using var writer = new StringWriter();
        serializer.Serialize(writer, swaggerDocument);
        var yaml = writer.ToString();
        await console.Output.WriteLineAsync(yaml);
    }

P.S. tried IReadOnlyList and it was not working in this case.

Console.ReadKey() implementation for SystemConsole

Generally I like the analyzer's warnings about usage of System.Console. However, in case of System.Console.ReadKey() there's no corresponding method in IConsole.

Either it may be added to IConsole, or the analyzer should stop worrying about ReadKey().

Print help text on specific exceptions

Exceptions related to user input should probably trigger help automatically so that besides being told "you didn't specify option --required" the user will also be shown what that option actually is.

Possibly also extend CommandException so that it's possible to request help when throwing that exception.

Force debug launch

Hm it is strange, but you merged pull request with active debug prompt and 3 days ago removed that functionality.
Is it merge errors or you decided to remove this functionality?

Global options & always parsing options as 'multiple'

Hello,

first of all, I quite like this library, it is really easy to grasp, which is rare in .net world.

There are 2 features though which are a blocker for me to consider using it, so just want to ask if I missed something or not.

Problem 1

One feature which I think is missing is global or persistent options, or did I missed it?
Specified on parent command, accessible to child command (maybe dependency injection can be used here?)

some useful examples

./cmd --log-level=debug subcommand --local-option  # set loggin level for all subcommands
./ginit --repo gitlab init --project-type rust ./my_project # set that all subcommands will be run against gitlab
./cmd -q subcommand # no output for all subcommands, only return codes
./cmd --json fetch 34 --include-images # return a JSON string for all subcommands

One way to have global options might be to enable them at the end (before arguments). like e.g. 'npm' handles it

npm -g ls --depth 1   # is an equivalent to
npm ls --depth 1 -g

Problem 2

This library is always parsing options as multiple values, which I think is really unusual (and essentially blocks global options).
I can't remember used it like that in case cli supported commands and subcommands.

How I think this feature is mostly implemented:

./cmd -i test.txt -i test.txt  # used e.g. in docker cli
# or
./cmd -i test.txt,test.txt     # used in a lot of cli apps + it is native to how powershell handles it
# or
./cmd -i=test.txt,tests.txt   # used e.g. in git cli

Just wondering what was the reasoning for this implementation, because going through some modern big CLIs like (kubectl, docker, dotnet, hugo, git, github, az, npm, yarn, cargo, pip, choco, scoop, etc.) it was hard to find similar behaviour. At least for me it is simply not intuitive and more or less unexpected.

Thank you for answers,
Stefan

Allow custom formatting of output

First of all, nice framework :)

I think it would be nice to allow custom formatting of output that is currently fixed. Output that I have seen so far (not an extensive list):

  • Argument type mismatch: Can't convert value [abc] to type [System.Int32].
  • Missing argument: One or more required options were not set: id.
  • Usage/help text

Add support for running under Microsoft.Extensions.Hosting.Host

Add support for configuring and launching the application under the .NET Generic Host.

Currently, this can be achieved in a sort of hacky way:

public static Task<int> Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    return new CliApplicationBuilder()
        .AddCommandsFromThisAssembly()
        .UseCommandFactory(schema => (ICommand)host.Services.GetRequiredService(schema.Type))
        .Build()
        .RunAsync(args);
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services.AddSingleton<IConsole, SystemConsole>();
        var typesThatImplementICommand = typeof(Program).Assembly.GetTypes().Where(x => typeof(ICommand).IsAssignableFrom(x));
        foreach (var t in typesThatImplementICommand)
            services.AddTransient(t);
    })
    .UseConsoleLifetime();

I envision this as something like

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureAsCliApplication()
    .ConfigureServices((hostContext, services) =>
    {
        // Add custom services here
    })
    .UseConsoleLifetime();

Then running it by either calling the existing Build().RunAsync() or .RunConsoleAsync() on IHostBuilderor adding a new.RunAsCliApplicationAsync()on eitherIHostBuilderorIHost` (or similar).

Ensure that user's commands don't have conflicts with built-in options

Command types should not contain options that resolve to one of the built-in options, i.e. --help/-h and --version (only on default command).

Currently this is not validated and will lead to undefined behavior (built-in options take precedence but both kind of options will still appear in help text).

Need to add validation and corresponding tests.

Show error when user provides an option/parameter that the command doesn't support

When the user supplies an unknown option/parameter, they should receive an error. This aligns with an optimal user experience, because the application shouldn't silently discard arguments that the user assumed would somehow change the behavior of the program.

Need to add a throw new CliFxException(...) statement somewhere in CommandSchema.InjectParameters and CommandSchema.InjectOptions.

Add corresponding tests.

Hide internals

A lot of implementation details are currently public. I believe the public API should be reduced to only include the interfaces/classes needed to operate the framework (e.g. CliApplicationBuilder, CommandAttribute etc.). Other code should be marked internal.

This is a benefit for the library developers, who can then easily refactor code in a non-breaking fashion, as well as consumer developers because the public API is more easily discoverable.

Pass-through arguments

Add support for path-through arguments.

Sometimes the application may act as a proxy to another application. An example of this is dotnet run which routes any arguments after -- directly to the executed application.

Example:

dotnet run -c Release -- arg1 arg2 --flag

Arguments arg1, arg2, --flag are passed as is to the executed application.

Allow [CommandArgumentSink] attribute on properties of type IEnumerable<string> or any other type that can be assigned from a string array or initialized with a string array (similar to how we do conversions currently). There can only be one such property.

Note: this has to play nicely with #38.

Open question:

  • Should arguments after -- only be consumed by argument sinks?
  • If not, then we need to determine how parameters/options and argument sinks should work together.

Report error when option not found

It would be nice to report an error to a user when he/she specifies an unknown option.

Actual
Let's say there is an optional option error-output. You run a command:

validate file --file C:\mydir\123.txt --schema C:\mydir\123.schema --errors-output C:\mydir\results

And for some reason, it doesn't behave as expected even though you don't see any errors.

Expected
You run this command and it tells you that option errors-output doesn't exist. You quickly fix the typo.

Add the ability to set exit code without displaying StackTrace details

So far working with CliFx has been excellent. I see this framework solving several of the issues I have with other options in the dotnet space today. Thank you @Tyrrrz

One edge I hit is the app that I am working on needs to set the exit code based on some application logic.

Within CliFx, it seems this can only be set by throwing an exception. I understand that as a design approach, but my need is to set the failure to a known error code without displaying a stack trace. This is an expected exception.

What I tried:

      if (WarningsAreErrors && result.Findings.Any())
      {
        // set the exit code
        throw new CommandException(string.Empty, exitCode: (int)AppExitCode.ErrorsFound);
      }

but the stack trace is still displayed:

CliFx.Exceptions.CommandException
   at UnderTest.FeatureLint.Commands.DefaultCommand.ThrowExitCodeIfError(FeatureLintResult result) in C:\dev\oss\under-test\undertest.featurelint\src\UnderTest.FeatureLint\Commands\DefaultCommand.cs:line 78
   at UnderTest.FeatureLint.Commands.DefaultCommand.ExecuteAsync(IConsole console) in C:\dev\oss\under-test\undertest.featurelint\src\UnderTest.FeatureLint\Commands\DefaultCommand.cs:line 60
   at CliFx.CliApplication.RunAsync(IReadOnlyList`1 commandLineArguments, IReadOnlyDictionary`2 environmentVariables)

So I am proposing a specific exception for this, say CommandExpectedException(open to feedback on the name)

This should just need the exception and an additional catch statement in CliApplication.RunAsync and I ready to create a PR if this is seen as a welcome change.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.