How to parse and execute a command-line style string?
Take a look at Mono.Options. It's currently part of Mono framework but can be downloaded and used as a single library.
You can obtain it here, or you can grab the current version used in Mono as a single file.
string data = null;
bool help = false;
int verbose = 0;
var p = new OptionSet () {
{ "file=", v => data = v },
{ "v|verbose", v => { ++verbose } },
{ "h|?|help", v => help = v != null },
};
List<string> extra = p.Parse (args);
The solution I generally use looks something like this. Please ignore my syntax errors... been a few months since I've used C#. Basically, replace the if/else/switch with a System.Collections.Generic.Dictionary<string, /* Blah Blah */>
lookup and a virtual function call.
interface ICommand
{
string Name { get; }
void Invoke();
}
//Example commands
class Edit : ICommand
{
string Name { get { return "edit"; } }
void Invoke()
{
//Do whatever you need to do for the edit command
}
}
class Delete : ICommand
{
string Name { get { return "delete"; } }
void Invoke()
{
//Do whatever you need to do for the delete command
}
}
class CommandParser
{
private Dictionary<string, ICommand> commands = new ...;
public void AddCommand(ICommand cmd)
{
commands.Insert(cmd.Name, cmd);
}
public void Parse(string commandLine)
{
string[] args = SplitIntoArguments(commandLine); //Write that method yourself :)
foreach(string arg in args)
{
ICommand cmd = commands.Find(arg);
if (!cmd)
{
throw new SyntaxError(String.Format("{0} is not a valid command.", arg));
}
cmd.Invoke();
}
}
}
class CommandParserXyz : CommandParser
{
CommandParserXyz()
{
AddCommand(new Edit);
AddCommand(new Delete);
}
}
Be aware that you can put attributes on parameters which might make things more readable, e.g.
public void TOPIC (
[ArgInfo("Specify topic ID...")] int Id,
[ArgInfo("Specify topic page...")] int? page)
{
...
}