Skip to content

Instantly share code, notes, and snippets.

@pwhe23
Created May 9, 2020 15:32
Show Gist options
  • Select an option

  • Save pwhe23/08c09e62238f3a4781b370bc72f1ecaa to your computer and use it in GitHub Desktop.

Select an option

Save pwhe23/08c09e62238f3a4781b370bc72f1ecaa to your computer and use it in GitHub Desktop.
System.CommandLine ConfigureFromClass example
#r "nuget: System.CommandLine, 2.0.0-beta1.20253.1"
//https://discoverdot.net/projects/dotnet-script
using System;
using System.CommandLine;
using System.CommandLine.Binding;
using System.CommandLine.Invocation;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
//var args = Args.ToArray();
var args = new string[] {
"-Name", "Paul",
"-Message", "Hello {0}!",
};
var command = new RootCommand();
ConfigureFromClass<Hello>(command, hello =>
{
Console.WriteLine(hello.Speak());
});
command.Invoke(args);
[Description("Say Hello")]
class Hello
{
[Description("Someone's name")]
public string Name { get; set; }
[Description("A simple message"), Required]
public string Message { get; set; }
public string Speak()
{
return string.Format(Message, Name);
}
};
private static void ConfigureFromClass<T>(Command command, Action<T> execute) where T : new()
{
var commandType = typeof(T);
command.Description = commandType
.GetCustomAttributes()
.OfType<DescriptionAttribute>()
.FirstOrDefault()
?.Description;
var props = commandType.GetProperties();
foreach (var prop in props)
{
var description = GetAttribute<DescriptionAttribute>(prop)?.Description;
var required = GetAttribute<RequiredAttribute>(prop) != null;
var option = new Option($"-{prop.Name}", description)
{
Required = required,
};
option.Argument = new Argument
{
ArgumentType = prop.PropertyType,
};
command.AddOption(option);
}
command.Handler = CommandHandler.Create((InvocationContext context) =>
{
var modelBinder = new ModelBinder<T>();
var cmd = new T();
modelBinder.UpdateInstance(cmd, context.BindingContext);
execute(cmd);
});
}
private static T GetAttribute<T>(PropertyInfo prop)
{
return prop
.GetCustomAttributes()
.OfType<T>()
.FirstOrDefault();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment