ArgsParser 4.0.5
See the version list below for details.
dotnet add package ArgsParser --version 4.0.5
NuGet\Install-Package ArgsParser -Version 4.0.5
<PackageReference Include="ArgsParser" Version="4.0.5" />
paket add ArgsParser --version 4.0.5
#r "nuget: ArgsParser, 4.0.5"
// Install ArgsParser as a Cake Addin #addin nuget:?package=ArgsParser&version=4.0.5 // Install ArgsParser as a Cake Tool #tool nuget:?package=ArgsParser&version=4.0.5
ArgsParser v4.0.5
Easy argument parsing for .Net applications (Core 3 or later). Full unit test coverage. Compatible with NetStandard 2.0. Available as a nuget package.
Contents
- Example usage
- Auto-generated helper text
- Supported features
- Example input and errors
- A more detailed example
Example usage
using ArgsParser;
var indent = 2;
var parser = new Parser(args)
.SupportsOption<int>("port", "Port to start the dev server on", 1337)
.RequiresOption<string>("read", "Folder to read the site from", "site")
.RequiresOption<string>("write", "Folder to write the result to")
.SupportsFlag("serve", "Start the site going in a dev server")
.SupportsFlag("force", "Overwrite any destination content");
parser.Help(indent);
parser.Parse();
if (parser.HasErrors)
{
parser.ShowErrors(indent);
return;
}
parser.ShowProvidedArguments(indent);
var startServing = parser.IsFlagProvided("serve");
var port = parser.GetOption<int>("port");
var read = parser.GetOption<string>("read");
Custom option validators
Standard validation is concerned with the presence/absence of arguments. Custom option validators allow you to also check their contents.
For example, here's a custom validator function that checks an option contains a CSV filename. This same function can be used repeatedly for multiple options. You can also declare inline functions using lambda but this is clearer for explanatory purposes.
/// <summary>Sample validator function which checks for a CSV filename.</summary>
/// <param name="key">Name of the argument.</param>
/// <param name="value">Content passed in.</param>
/// <returns>A list of any errors.</returns>
private List<string> IsCSV(string key, object value)
{
// In reality we would also need null checks etc.
var errs = new List<string>();
var ext = Path.GetExtension($"{value}").ToLowerInvariant();
if (ext != ".csv") errs.Add($"{key} does not hold a CSV filename.");
return errs;
}
The signature is always the same. Your validator receives an option name and value, then returns a list of zero or more error messages which will be automatically gathered alongside the standard errors. The value is an object
because your options are generically typed and therefore there is no guarantee what the incoming type will be. (It's your codebase; if you know which options your validator is being registered with you can make casting assumptions.)
Once you have a validator you need to register it:
var parser = new Parser(args)
.SupportsOption<string>("filename", "A CSV filename")
.AddCustomOptionValidator("filename", IsCSV);
parser.Parse();
Accessing errors is described further on.
Auto-generated helper text
In the examples below, 2
is a left indent of two spaces.
Parser.Help(2);
(Required options come first, then optional options, then flags.)
-read text * Folder to read the site from [site]
-write text * Folder to write the result to
-apr number Annual interest [3.596]
-fee number Monthly charge [19.50]
-port integer Port to start the dev server on [1337]
-secure true/false Serve on HTTPS? [True]
-until datetime When to stop serving [22/08/2023 06:28:13]
-force Overwrite any destination content
-serve Start the site going in a dev server
* means required, values in square brackets are defaults
Parser.ShowErrors(2)
Option missing: write
Unknown flag: run
Parser.ShowProvidedArguments(2);
-port 3000
-read in.txt
-serve
-force
Supported features
- Display help showing supported flags/options
- Also shows argument types, defaults, and optional legend
- Display all errors
- Display all provided input arguments
- Required named option/values
- Optional named option/values
- Optional named flags
- Default option values
- Option types support any
IConvertable
, includingint
,bool
,DateTime
- Accepts either
-
or--
prefixes - Provides two collections of error messages
- Expectation errors
- Missing required options
- Custom option validator errors
- Argument errors
- Option values of incorrect type
- This may be switched to be an Expectation error in a future change
- Unexpected values (not with an option)
- Unknown flags or options
- Option values of incorrect type
- Expectation errors
Example input and errors
These assume the arguments defined in the Example usage section above.
Example user input:
MyApp -run data "Site Title" --serve -ignore -port 3000
There are a few things wrong here with this input:
- The
-write
option is required but not provided - The provided
-run
option is not defined - The
"Site Title"
argument has no option name preceeding it - The provided
-ignore
flag is not defined
Whilst the -read
option is missing there is no error logged - it was defined with a default value of site
and so the requirement is automatically met.
Errors come in two collections (the property Parser.HasErrors
will be true
if either has entries):
ExpectationErrors
are where specific expectations are not met (eg a missing required option) so the relevant option/flag whose expectations are not being met is known- Custom option validator errors will also be in here
ArgumentErrors
are where something was provided but there were general issues with it (eg a value provided without an option name preceeding it) so there is no certainty as to what was intended by the input given and we cannot definitively tie it to a specific option/flag
Based on the example above the errors (as key/value pairs) will be as follows:
ExpectationErrors
keyed by the name of the related option/flagwrite
⇒Option missing: write
ArgumentErrors
keyed by the 0-based offset into the arguments provided0
⇒Unknown option: run
2
⇒Unexpected value: Site Title
4
⇒Unknown flag: ignore
A more detailed example
(The assertions included below use NUnit. See the test project.)
var args = new string[] { "-run", "data", "Site Title", "--serve", "-ignore", "-port", "3000" };
var parser = new Parser(args)
.SupportsOption<int>("port", "Port to start the dev server on", 1337)
.RequiresOption<string>("read", "Folder to read the site from", "site")
.RequiresOption<string>("write", "Folder to write the result to")
.SupportsFlag("serve", "Start the site going in a dev server")
.SupportsFlag("force", "Overwrite any destination content")
.Help();
var result = parser.Parse();
Assert.AreEqual(4, result.ExpectationErrors.Count + result.ArgumentErrors.Count);
Assert.Contains("Option missing: write", result.ExpectationErrors.Values.ToList());
Assert.Contains("Unknown option: run", result.ArgumentErrors.Values.ToList());
Assert.Contains("Unexpected value: Site Title", result.ArgumentErrors.Values.ToList());
Assert.Contains("Unknown flag: ignore", result.ArgumentErrors.Values.ToList());
Assert.IsTrue(result.IsOptionProvided("port"));
Assert.AreEqual(3000, result.GetOption<int>("port"));
Assert.IsTrue(result.IsOptionProvided("read"));
Assert.AreEqual("site", result.GetOption<string>("read"));
Assert.IsFalse(result.IsOptionProvided("write"));
Assert.AreEqual(null, result.GetOption<string>("write"));
Assert.IsTrue(result.IsFlagProvided("serve"));
Assert.IsFalse(result.IsFlagProvided("force"));
Copyright K Cartlidge 2020-2023.
Licensed under GNU AGPLv3 (see here for more details). See the CHANGELOG for current status.
Product | Versions 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. |
-
.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.