Skip to content

Instantly share code, notes, and snippets.

@robhol robhol/ExampleOptions.cs
Last active Aug 29, 2015

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using RCommandLine;
namespace ExampleApplication
{
[
HasCommand(typeof(ReadOptions), Description = "Read a file"), //Name default: read - this is set by the class name minus a trailing "Options" (unless you specify it yourself, of course.)
HasCommand(typeof(WriteOptions), Description = "Write a file") //Name default: write
]
class ExampleOptions
{
public abstract class FileOptions
{
[Parameter(0, Description = "The file to act upon")] //Name default: Path (Will only actually show in help text)
public string Path { get; set; }
[Flag('F', longName: "", Description = "The format to use in a file operation"), Optional(Default = "foo")] //Name default: format (--format) - since "" is given, no long name will be used.
public string Format { get; set; }
}
public class ReadOptions : FileOptions
{
[Flag('c', Description = "The size of individual chunks being read"), Optional(Default = 2048)] // (--chunk-size)
public int ChunkSize { get; set; }
}
public class WriteOptions : FileOptions
{
[Flag('d', Description = "Whether or not to include debug information in the output")]
public bool DebugInfo { get; set; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using RCommandLine;
namespace ExampleApplication
{
class Program
{
static void Main(string[] args)
{
//Step 1: define Options classes (see ExampleOptions.cs)
//Step 2: instantiate Parser with desired Options type and settings
var parser = new Parser<ExampleOptions>
{
BaseCommandName = System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location),
AutomaticCommandList = true,
AutomaticUsage = true,
AutomaticHelp = true
};
//Step 3: Parse() and output consumption!
var result = parser.Parse();
if (result != ParseResult.None)
{
switch (result.Command)
{
case "read":
{
var x = result.Options as ExampleOptions.ReadOptions;
// your logic here
break;
}
case "write":
{
var x = result.Options as ExampleOptions.WriteOptions;
break;
}
default:
{
//by design, AutomaticCommandList doesn't catch "invalid" commands, just empty ones.
result.ShowCommandList();
break;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.