Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Class-first framework for building command-line interfaces

License

NotificationsYou must be signed in to change notification settings

Tyrrrz/CliFx

Repository files navigation

StatusMade in UkraineBuildCoverageVersionDownloadsDiscordFuck 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 yourimplicit agreement to all the following statements:

  • Youcondemn Russia and its military aggression against Ukraine
  • Yourecognize that Russia is an occupant that unlawfully invaded a sovereign state
  • Yousupport Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas
  • Youreject 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 theMain() method so that it delegates the execution to an instance ofCliApplication.You can useCliApplicationBuilder to simplify the process of creating and configuring an application:

usingCliFx;publicstaticclassProgram{publicstaticasyncTask<int>Main()=>awaitnewCliApplicationBuilder().AddCommandsFromThisAssembly().Build().RunAsync();}

Warning:Ensure that yourMain() method returns the integer exit code provided byCliApplication.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 callingCliApplication.RunAsync(),CliFx resolves command-line arguments and environment variables fromEnvironment.GetCommandLineArgs() andEnvironment.GetEnvironmentVariables() respectively.You can also provide them manually using one of the alternative overloads.

The code above usesAddCommandsFromThisAssembly() 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 theICommand interface and annotate it with the[Command] attribute:

usingCliFx;usingCliFx.Attributes;[Command(Description="Calculates the logarithm of a value.")]publicclassLogCommand:ICommand{// Order: 0[CommandParameter(0,Description="Value whose logarithm is to be found.")]publicrequireddoubleValue{get;init;}// Name: --base// Short name: -b[CommandOption("base",'b',Description="Logarithm base.")]publicdoubleBase{get;init;}=10;publicValueTaskExecuteAsync(IConsoleconsole){varresult=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.returndefault;}}

In order to implementICommand, the class needs to define anExecuteAsync(...) 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 ofIConsole, which is an abstraction around the system console.Use this abstraction in place ofSystem.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 100004

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

$dotnet myapp.dll 729 -b 36

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

$dotnet myapp.dll -b 10Missing 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 --helpMyApp v1.0USAGE  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 commandcmd (assuming it's a command) with parameterabc and sets option'o' without value

Additionally, argument parsing inCliFx 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 ofmyapp -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 andoptions.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 settingIsRequired = true on the corresponding attribute or by adding therequired keyword to the property declaration (introduced in C# 11):

      // Any option can be required or optional without restrictions[CommandOption("foo")]publicrequiredstringRequiredOption{get;init;}
    • To make a parameter optional, you can setIsRequired = 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)]publicstring?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 asIReadOnlyList<T>:

      // Any option can be non-scalar[CommandOption("foo")]publicrequiredIReadOnlyList<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)]publicrequiredIReadOnlyList<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")]publicrequiredstringOptionWithFallback{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 astring (FileInfo,DirectoryInfo, etc.)
    • Types with a staticParse(...) method accepting astring and optionally aIFormatProvider (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]publicclassFileSizeCalculatorCommand: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)]publicrequiredIReadOnlyList<FileInfo>Files{get;init;}publicValueTaskExecuteAsync(IConsoleconsole){vartotalSize=Files.Sum(f=>f.Length);console.Output.WriteLine($"Total file size:{totalSize} bytes");returndefault;}}
$dotnet myapp.dll file1.bin file2.exeTotal file size: 186368 bytes

Custom conversion

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

// Maps 2D vectors from AxB notationpublicclassVectorConverter:BindingConverter<Vector2>{publicoverrideVector2Convert(string?rawValue){if(string.IsNullOrWhiteSpace(rawValue))returndefault;varcomponents=rawValue.Split('x','X',';');varx=int.Parse(components[0],CultureInfo.InvariantCulture);vary=int.Parse(components[1],CultureInfo.InvariantCulture);returnnewVector2(x,y);}}[Command]publicclassSurfaceCalculatorCommand:ICommand{// Custom converter is used to map raw argument values[CommandParameter(0,Converter=typeof(VectorConverter))]publicrequiredVector2PointA{get;init;}[CommandParameter(1,Converter=typeof(VectorConverter))]publicrequiredVector2PointB{get;init;}[CommandParameter(2,Converter=typeof(VectorConverter))]publicrequiredVector2PointC{get;init;}publicValueTaskExecuteAsync(IConsoleconsole){vara=(PointB-PointA).Length();varb=(PointC-PointB).Length();varc=(PointA-PointC).Length();varp=(a+b+c)/2;varsurface=Math.Sqrt(p*(p-a)*(p-b)*(p-c));console.Output.WriteLine($"Triangle surface area:{surface}");returndefault;}}
$dotnet myapp.dll 0x0 0x10 10x0Triangle 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.

WithCliFx, 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]publicclassDefaultCommand:ICommand{// ...}// Child of default command[Command("cmd1")]publicclassFirstCommand:ICommand{// ...}// Child of default command[Command("cmd2")]publicclassSecondCommand:ICommand{// ...}// Child of FirstCommand[Command("cmd1 sub")]publicclassSubCommand:ICommand{// ...}

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

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

$dotnet myapp.dll --helpMyApp v1.0USAGE  dotnet myapp.dll [options]  dotnet myapp.dll [command] [...]OPTIONS  -h|--help         Shows help text.  --version         Shows version information.COMMANDS  cmd1              Subcommands: cmd1 sub.  cmd2You 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 --helpUSAGE  dotnet myapp.dll cmd1 [options]  dotnet myapp.dll cmd1 [command] [...]OPTIONS  -h|--help         Shows help text.COMMANDS  subYou 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 inCliFx do not directly return exit codes, but instead communicate execution errors viaCommandException.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]publicclassDivideCommand:ICommand{[CommandOption("dividend")]publicrequireddoubleDividend{get;init;}[CommandOption("divisor")]publicrequireddoubleDivisor{get;init;}publicValueTaskExecuteAsync(IConsoleconsole){if(Math.Abs(Divisor)<double.Epsilon){// This will print the error and set exit code to 133thrownewCommandException("Division by zero is not supported.",133);}varresult=Dividend/Divisor;console.Output.WriteLine(result);returndefault;}}
$dotnet myapp.dll --dividend 10 --divisor 0Division 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, callconsole.RegisterCancellationHandler() to register the signal handler and obtain the correspondingCancellationToken.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]publicclassCancellableCommand:ICommand{privateasyncValueTaskDoSomethingAsync(CancellationTokencancellation){awaitTask.Delay(TimeSpan.FromMinutes(10),cancellation);}publicasyncValueTaskExecuteAsync(IConsoleconsole){// Make the command cancellation-awarevarcancellation=console.RegisterCancellationHandler();// Execute some long-running cancellable operationawaitDoSomethingAsync(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

BecauseCliFx 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 calledITypeActivator that determines how to create a new instance of a given type.

The default implementation ofITypeActivator 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 customITypeActivator or a factory delegate to theUseTypeActivator(...) method when building the application:

publicstaticclassProgram{publicstaticasyncTask<int>Main()=>awaitnewCliApplicationBuilder().AddCommandsFromThisAssembly().UseTypeActivator(type=>{varinstance=MyTypeFactory.Create(type);returninstance;}).Build().RunAsync();}

This method also supportsIServiceProvider 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 useMicrosoft.Extensions.DependencyInjection as the type activator inCliFx:

publicstaticclassProgram{publicstaticasyncTask<int>Main()=>awaitnewCliApplicationBuilder().AddCommandsFromThisAssembly().UseTypeActivator(commandTypes=>{varservices=newServiceCollection();// Register servicesservices.AddSingleton<MyService>();// Register commandsforeach(varcommandTypeincommandTypes)services.AddTransient(commandType);returnservices.BuildServiceProvider();}).Build().RunAsync();}

Note:If you want to use certain advanced features provided byMicrosoft.Extensions.DependencyInjection, you may need to do a bit of extra work to configure the container properly.For example, to leverage support for keyed services, you need tomanually register an implementation ofIKeyedServiceProvider.

Testing

Thanks to theIConsole abstraction,CliFx commands can be easily tested in isolation.While an application running in production would rely onSystemConsole to interact with the real console, you can useFakeConsole andFakeInMemoryConsole in your tests to execute your commands in a simulated environment.

For example, imagine you have the following command:

[Command]publicclassConcatCommand:ICommand{[CommandOption("left")]publicstringLeft{get;init;}="Hello";[CommandOption("right")]publicstringRight{get;init;}="world";publicValueTaskExecuteAsync(IConsoleconsole){console.Output.Write(Left);console.Output.Write(' ');console.Output.Write(Right);returndefault;}}

To test it, you can instantiate the command in code with the required values, and then pass an instance ofFakeInMemoryConsole toExecuteAsync(...):

// Integration test at the command level[Test]publicasyncTaskConcatCommand_executes_successfully(){// Arrangeusingvarconsole=newFakeInMemoryConsole();varcommand=newConcatCommand{Left="foo",Right="bar"};// Actawaitcommand.ExecuteAsync(console);// AssertvarstdOut=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]publicasyncTaskConcatCommand_executes_successfully(){// Arrangeusingvarconsole=newFakeInMemoryConsole();varapp=newCliApplicationBuilder().AddCommand<ConcatCommand>().UseConsole(console).Build();varargs=new[]{"--left","foo","--right","bar"};varenvVars=newDictionary<string,string>();// Actawaitapp.RunAsync(args,envVars);// AssertvarstdOut=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 -oAttach 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 bar2Command-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 callingAllowDebugMode(...) andAllowPreviewMode(...) methods onCliApplicationBuilder:

varapp=newCliApplicationBuilder().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".


[8]ページ先頭

©2009-2025 Movatter.jp