Created
April 16, 2013 20:59
-
-
Save xcud/5399602 to your computer and use it in GitHub Desktop.
Extends Mono.Options, a better command line parser.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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