Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active October 10, 2015 17:27
Show Gist options
  • Save thekid/0d1d0aebba3bcc131699 to your computer and use it in GitHub Desktop.
Save thekid/0d1d0aebba3bcc131699 to your computer and use it in GitHub Desktop.
XP Subcommand / Options / Arguments parsing
using System;
using System.Collections.Generic;
interface Command
{
int Run(Dictionary<string, string> options, IList<string> arguments);
}
using System;
using System.Collections.Generic;
class run : Command
{
public int Run(Dictionary<string, string> options, IList<string> arguments)
{
Console.Write("run(");
foreach (var pair in options)
{
Console.Write("{0}=\"{1}\" ", pair.Key, pair.Value);
}
Console.WriteLine("arguments=[{0}])", String.Join(", ", arguments));
return 0;
}
}
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
class xp
{
private static Dictionary<string, string> subcommands = new Dictionary<string, string>()
{
{ "-e", "eval" },
{ "-v", "version" },
{ "-w", "write" },
{ "-d", "dump" }
};
public static int Main(string[] args)
{
var offset = 0;
var subcommand = "run";
var options = new Dictionary<string, string>()
{
{ "include_path", "" }
};
for (var i = 0; i < args.Length; i++)
{
if ("-cp" == args[i])
{
options["include_path"] += ";" + args[++i];
}
else if (subcommands.ContainsKey(args[i]))
{
subcommand = subcommands[args[i]];
offset = ++i;
break;
}
else
{
subcommand = args[i];
offset = ++i;
break;
}
}
try
{
var command = Assembly.LoadFrom(subcommand + ".dll").GetType(subcommand);
var exit = command.GetMethod("Run").Invoke(Activator.CreateInstance(command, null), new object[]
{
options,
new ArraySegment<string>(args, offset, args.Length - offset)
});
return exit is int ? (int)exit : 0x00;
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("*** No such subcommand `{0}'", subcommand);
return 0xff;
}
}
}
@thekid
Copy link
Author

thekid commented Oct 10, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment