Skip to content

Instantly share code, notes, and snippets.

@itn3000
Created March 25, 2022 10:04
Show Gist options
  • Save itn3000/399b5de2367a0504a0d69ff13538e497 to your computer and use it in GitHub Desktop.
Save itn3000/399b5de2367a0504a0d69ff13538e497 to your computer and use it in GitHub Desktop.
sandbox for System.CommandLine( https://github.com/dotnet/command-line-api )
using System.CommandLine;
using System.CommandLine.Binding;
var opt1 = new Option<string>(new string[]{ "--opt1", "-o1" }, "this is option1");
var opt2 = new Option<int>(new string[]{ "--opt2", "-o2" }, "this is option2");
var rootcmd = new RootCommand("this is root");
rootcmd.Add(opt1);
rootcmd.Add(opt2);
rootcmd.AddCommand(CreateCommand1());
rootcmd.SetHandler((string x, int y) =>
{
Console.WriteLine($"opt1 = {x}, opt2 = {y}");
}, opt1, opt2);
rootcmd.Invoke(args);
Command CreateCommand1()
{
var opt1 = new Option<string[]>("--subopt1", "this is subopt1");
var cmd = new Command("sub1", "this is subcmd");
cmd.AddOption(opt1);
cmd.SetHandler<Moge>(x =>
{
Console.WriteLine($"opt1 = {x}");
}, new MyBinder(opt1));
return cmd;
}
record class Moge(string X, int Y);
class MyBinder : BinderBase<Moge>
{
Option<string[]> _Option1;
public MyBinder(Option<string[]> opt1)
{
_Option1 = opt1;
}
protected override Moge GetBoundValue(BindingContext bindingContext)
{
var value = bindingContext.ParseResult.GetValueForOption<string[]>(_Option1);
if(value != null && value.Length > 0)
{
return new Moge(string.Join("|", value), value.Length);
}
else
{
return new Moge("", 10);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment