fclp / fluent-command-line-parser

A simple, strongly typed .NET C# command line parser library using a fluent easy to use interface
Other
533 stars 86 forks source link

Auto-setup using reflection #112

Closed astrohart closed 3 years ago

astrohart commented 3 years ago

I'd like to just have the parser eat my custom command line info class and not have to call Setup for each and every argument. I'd be fine decorating the properties of my POCO with attributes that would allow the library to be used like:

public class ApplicationArguments
{
   [Option(...)]
   public int RecordId { get; set; }

   [Option(...)]
   public bool Silent { get; set; }

   [Option(...)]
   public string NewValue { get; set; }
}

The [Option()] (or whatever you want to call them) would do all the calls to Setup for me, so that then I just fling my ApplicationArguments POCO at the ctor of the FluentCommandLineParser class through its generic type parameter and then call Parse right away:

var appArgs = new FluentCommandLineParser<ApplicationArguments>().Parse(args).Object;

Sooo much less code than:

static void Main(string[] args)
{
   // create a generic parser for the ApplicationArguments type
   var p = new FluentCommandLineParser<ApplicationArguments>();

   // specify which property the value will be assigned too.
   p.Setup(arg => arg.RecordId)
    .As('r', "record") // define the short and long option name
    .Required(); // using the standard fluent Api to declare this Option as required.

   p.Setup(arg => arg.NewValue)
    .As('v', "value")
    .Required();

   p.Setup(arg => arg.Silent)
    .As('s', "silent")
    .SetDefault(false); // use the standard fluent Api to define a default value if non is specified in the arguments

   var result = p.Parse(args);

   if(result.HasErrors == false)
   {
      // use the instantiated ApplicationArguments object from the Object property on the parser.
      application.Run(p.Object);
   }
}

And more extensible, too --- since I can then just add new properties to the POCO.

siywilliams commented 3 years ago

One of the reasons I started Fluent Command Line Parser is because I didn't like using any of the existing CLPs that required attributes decoration. I wanted to keep the CLP logic completely seperate and I felt that attributes didn't allow that.

Plus I liked using fluent api style, hence the name.