Skip to content

Instantly share code, notes, and snippets.

@xcud
Created April 16, 2013 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xcud/5399602 to your computer and use it in GitHub Desktop.
Save xcud/5399602 to your computer and use it in GitHub Desktop.
Extends Mono.Options, a better command line parser.
using System;
using System.Linq;
using Mono.Options;
namespace xcud
{
public class AttributedOptionSet : OptionSet
{
public static T Parse<T>(string[] args) where T : AttributedOptionSet, new()
{
var retval = new T();
typeof(T).GetFields().ToList().ForEach(propertyInfo =>
{
var propertyAttribs = propertyInfo.GetCustomAttributes(false);
var optionAttribute =
propertyAttribs.FirstOrDefault(a => a is OptionAttribute) as OptionAttribute;
if (optionAttribute == null)
return;
retval.Add(optionAttribute.Prototype, optionAttribute.Description, p =>
{
if (optionAttribute.Prototype.EndsWith("="))
propertyInfo.SetValue(retval, p);
else
propertyInfo.SetValue(retval, true);
});
});
retval.Parse(args);
return retval;
}
}
public class OptionAttribute : Attribute
{
public string Prototype = null;
public string Description = null;
public OptionAttribute(string prototype, string description)
{
Prototype = prototype;
Description = description;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment