Last active
October 10, 2015 17:27
-
-
Save thekid/0d1d0aebba3bcc131699 to your computer and use it in GitHub Desktop.
XP Subcommand / Options / Arguments parsing
This file contains 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.Collections.Generic; | |
interface Command | |
{ | |
int Run(Dictionary<string, string> options, IList<string> arguments); | |
} |
This file contains 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.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; | |
} | |
} |
This file contains 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.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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See xp-framework/rfc#303