Mechiru.Command is the simplest command line argument parser.
🚧 This library is implemented for container applications and has some limitations. 🚧
record Opt(
[Option] string Foo,
[Option] bool Bar
);
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ dotnet run --foo hello --bar
Opt { Foo = hello, Bar = True }
.NET 5+
You can also use the standard argument parser instead of relying on a third party library.
Check this documentation for details.
- Support environment variables commandlineparser/commandline#677
- Default value from function through interface
- Record class friendly
record Opt([Option(Required = true)] string Foo);
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ dotnet run
Unhandled exception. System.ArgumentException: required option not specified: `foo`
at Mechiru.Command.ArgumentParser.ParseInner(IEnumerable`1 args, ArgSpec[] specs)
at Mechiru.Command.ArgumentParser.Parse[T](IEnumerable`1 args)
at Mechiru.Command.ArgumentParser.ParseDefault[T]()
at test.Program.Main(String[] args) in /tmp/test/Program.cs:line 12
record Opt([Option(Env = true)] string Foo);
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ FOO=fuga dotnet run
Opt { Foo = fuga }
You can also override the name of the environment variable:
record Opt([Option(Env = "MY_FOO")] string Foo);
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ MY_FOO=my-fuga dotnet run
Opt { Foo = my-fuga }
record Opt([Option(Default = "hoge")] string Foo);
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ dotnet run
Opt { Foo = hoge }
You can also set default value from object:
record Opt([Option(Default = 20)] int Age);
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ dotnet run
Opt { Age = 20 }
You can also set default value from function through interface:
record Opt([Option(Default = typeof(MyDefaultValue))] string Foo);
class MyDefaultValue : IDefault
{
public object Default() => "value from function";
}
Console.WriteLine(ArgumentParser.ParseDefault<Opt>());
$ dotnet run
Opt { Foo = value from function }
record Opt([Option(Parser = typeof(JsonArrayParser))] string[] Values);
class JsonArrayParser : IParser
{
public object Parse(string s) => JsonSerializer.Deserialize<string[]>(s)!;
}
var opt = ArgumentParser.ParseDefault<Opt>();
Console.WriteLine(string.Join(',', opt.Values));
$ dotnet run --values '["foo", "fuga", "hoge"]'
foo,fuga,hoge
Other examples can be found here.
This library is under the MIT License.