CommandLineFluent 1.5.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package CommandLineFluent --version 1.5.0
NuGet\Install-Package CommandLineFluent -Version 1.5.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="CommandLineFluent" Version="1.5.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add CommandLineFluent --version 1.5.0
#r "nuget: CommandLineFluent, 1.5.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 CommandLineFluent as a Cake Addin
#addin nuget:?package=CommandLineFluent&version=1.5.0

// Install CommandLineFluent as a Cake Tool
#tool nuget:?package=CommandLineFluent&version=1.5.0

CommandLineFluent

A .NET Command Line Parsing library which is set up and parsed using fluent syntax. It parses command line arguments into strongly-typed classes which you define. Supports conversion, validation, default values, and automatic help/usage text. It also supports invoking awaitable or asynchronous actions with the classes you define.

Terminology

An Option is a piece of unique text, followed by another. For example: foo.exe -o option

A Value is a lone piece of text. For example: foo.exe value

A Switch is a piece of unique text, whose presence dictates on/off. For example: foo.exe -s

Examples

Basic Parsing

Create a class with public getters/setters and a public parameterless constructor. This class will hold the parsed arguments.

Then, FluentParser has to be configured using the FluentParserBuilder to map to that class' properties. Below is a simple example, which parses arguments into a ProcessFile instance.

public class ProcessFile
{
	public string OutputFile { get; set; }
	public bool Frobulate { get; set; }
	public string InputFile { get; set; }
}
FluentParser fp = new FluentParserBuilder()
	.Configure(config =>
	{
		config.ShowHelpAndUsageOnFailure(); // Goes to the console by default
		config.UseHelpSwitch("-?", "--help"); // If encountered, the Parser immediately stops and writes help/usage
	})
	.WithoutVerbs<ProcessFile>(verbless =>
	{
		verbless.WithHelpText("Does something to the input file");

		// ValueProperty is a string
		verbless.AddValue()
			.ForProperty(theClass => theClass.InputFile)
			.WithName("Input File")
			.WithHelpText("The file which has to be processed")
			.IsRequired();
		
		// Frobulate is a bool
		verbless.AddSwitch("-f", "--frobulate")
			.ForProperty(theClass => theClass.Frobulate)
			.WithHelpText("If provided, the file will be frobulated");
		
		// OutputFile is a string
		verbless.AddOption("-o", "--output")
			.ForProperty(theClass => theClass.OutputFile)
			.WithName("Output file")
			.WithHelpText("The output file")
			.IsRequired();
	}).Build();
	
	fp.Parse(args)
		.OnFailure(errors => MyFailureMethod(errors))
		.OnSuccess<ProcessFile>(processFileInstance => MyFrobulationMethod(processFileInstance));

Configuring the Parser

Most of the time, you can use defaults. They are: A default short and long prefix (- and --, respectively), help switches (-? and --help), and writes Help and Usage text to the console on any parsing errors (either verb-specific or overall).

Because the defaults involve setting a default short and long name prefix, you don't need to include these prefixes when adding Options and Switches.

new FluentParserBuilder().Configure(config => config.ConfigureWithDefaults())
	.WithoutVerbs<ProcessFile>(verbless =>
	{
		verbless.AddSwitch("f", "frobulate"); // Defaults automatically prefix these, so they become -f and --frobulate
	};

Optional arguments

By using IsOptional(defaultValue), we denote that an Option or Value is not required. If it does not appear, it will be assigned defaultValue. Switches can be given a default by calling WithDefaultValue(defaultValue).

All Options and Values are, by default, required. Switches are always optional.

verbless.AddOption("-p", "--parameters")
	.ForProperty(theClass => theClass.ParametersFile)
	.WithName("Parameters file")
	.WithHelpText("A file which contains extra parameters defining how to frobulate the file")
	.IsOptional("defaultFile.frob"); // If not provided, property will be assigned this string

Validators

You can also add some validation. CommandLineFluent comes with some basic validators. For example, Validators.FileExists is a method that takes a string and makes sure that it is a file which exists.

Validators return a string, which is the error message. Return null to indicate validation was successful.

verbless.AddValue()
	.ForProperty(theClass => theClass.InputFile)
	.WithName("Input File")
	.WithValidator(Validators.FileExists) // <-- Added a validator here
	.WithHelpText("The file which has to be processed")
	.IsRequired();

Converters

Converters take the raw string value and convert it to something else. They are automatically invoked when parsing.

Constructing a Converted<T> instance like the below indicates success. An optional second parameter denotes the error message; if provided, conversion is considered to have failed.

verbless.AddValue<FileInfo>()
	.ForProperty(theClass => theClass.InputFileInfo)
	.WithName("Input File")
	.WithConverter(rawValue =>
	{
		if(File.Exists(rawValue))
		{
			return new Converted<FileInfo>(new FileInfo(rawValue));
		}
		else
		{
			return new Converted<FileInfo>(null, $"The file {rawValue} doesn't exist");
		}
	})
	.WithHelpText("The file which has to be processed")
	.IsOptional(new FileInfo()); // Optional values will also be typed as FileInfo objects

Awaitable/Asynchronous

If your target methods are awaitble (i.e. They return a Task object) then you are able to invoke them and await the Task or invoke them asynchronously. The Invoke() method will return the Task your method returns, and the InvokeAsync() method will await the Task your method returns.

FluentParser fp = new FluentParserBuilder()
	.Configure(config =>
	{
		config.ConfigureWithDefaults();
	})
	.WithoutVerbs<ProcessFile>(verbless =>
	{
		// ValueProperty is a string
		verbless.AddValue()
			.ForProperty(theClass => theClass.InputFile)
			.WithName("Input File")
			.WithHelpText("The file which has to be processed")
			.IsRequired();
	}).Build();

	// Await the task that MyFrobulationMethodAsync returns, .Invoke() will just return the Task without awaiting it
	await fp.ParseAwaitable(args)
		.OnSuccess<ProcessFile>(processFileInstance => MyFrobulationMethodAsync(processFileInstance))
		.Invoke();

	// Await the task that MyFrobulationMethodAsync returns, .InvokeAsync() will await the Task
	await fp.ParseAwaitable(args)
		.OnSuccess<ProcessFile>(processFileInstance => MyFrobulationMethodAsync(processFileInstance))
		.InvokeAsync();

Multiple Verbs

It's possible to set up multiple different verbs, e.g. git add and git pull.

Adding Verbs entails the exact same setup as above, except you use need one .AddVerb<VerbClass>(verbName, verbConfig) call per verb. The verb names have to be unique.

// Verb Names don't have to be const fields, but it's easier to manage
public class FrobulateFile
{
	public const string verbName = "frobulate";
	public string InputFile { get; set; }
}
public class BojangleFile
{
	public const string verbName = "bojangle";
	public string InputFile { get; set; }
}
FluentParser fp = new FluentParserBuilder()
	.Configure(config =>
	{
		config.ShowHelpAndUsageOnFailure(); // Goes to the console by default
		config.UseHelpSwitch("-?", "--help"); // If we encounter this, we'll immediately stop and write out some help
	})
	.AddVerb<FrobulateFile>(FrobulateFile.verbName, verb =>
	{
		verb.AddOption("-i", "--inputFile")
			.ForProperty(o => o.InputFile);
	})
	.AddVerb<BojangleFile>(BojangleFile.verbName, verb =>
	{
		verb.AddOption("-i", "--inputFile")
			.ForProperty(o => o.InputFile);
	}).Build();
	
	fp.Parse(args)
		.OnSuccess<FrobulateFile>(frob => MyFrobulationMethod(frob))
		.OnSuccess<BojangleFile>(boj => MyBojanglingMethod(boj));
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 netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  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.
  • .NETStandard 2.0

    • No dependencies.

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
2.6.0 458 11/15/2021
2.5.0 932 6/8/2021
2.4.1 368 5/23/2021
2.4.0 319 4/29/2021
2.3.3 365 11/26/2020
2.3.2 384 11/17/2020
2.3.1 422 11/9/2020
2.3.0 474 10/30/2020
2.2.1 416 9/24/2020
2.2.0 404 9/23/2020
2.1.1 447 9/11/2020
2.1.0 466 8/29/2020
2.0.2 455 8/23/2020
2.0.1 407 8/21/2020
2.0.0 418 8/19/2020
1.7.3 596 2/23/2020
1.7.2 486 12/3/2019
1.7.1 479 11/15/2019
1.7.0 473 11/14/2019
1.6.0 509 10/31/2019
1.5.0 484 10/24/2019
1.4.0 495 10/16/2019
1.3.0 509 10/15/2019
1.2.0 490 10/3/2019
1.1.0 497 9/17/2019