Skip to content

mechiru/Mechiru.Command

Repository files navigation

Mechiru.Command

ci pub nuget

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 }

TargetFrameworks

.NET 5+

Notice

You can also use the standard argument parser instead of relying on a third party library.
Check this documentation for details.

Features:

Examples

Required arguments

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

Environment variables

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 }

Default values

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 }

Custom parsing

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.

Lisence

This library is under the MIT License.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages