78 lines
2.6 KiB
C#
78 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
|
|
namespace RecrownedAthenaeum.Tools.CommandProcessor
|
|
{
|
|
internal class CommandEngine
|
|
{
|
|
public bool running;
|
|
public readonly Dictionary<string, ICommandEngineCommand> commands;
|
|
|
|
public CommandEngine()
|
|
{
|
|
commands = new Dictionary<string, ICommandEngineCommand>();
|
|
}
|
|
|
|
internal void Run()
|
|
{
|
|
while (running)
|
|
{
|
|
string command = Console.ReadLine();
|
|
try
|
|
{
|
|
Process(command);
|
|
|
|
}
|
|
catch (ArgumentException ae)
|
|
{
|
|
Console.WriteLine("Error: " + ae.Message);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Process(string commandAndArguments)
|
|
{
|
|
string command = commandAndArguments;
|
|
string[] arguments = null;
|
|
|
|
if (commandAndArguments.Contains(' '))
|
|
{
|
|
command = command.Remove(command.IndexOf(' '));
|
|
if (!commands.ContainsKey(command)) throw new ArgumentException("Command not found.");
|
|
string[] argumentsSplit = commandAndArguments.Remove(command.Length).Split(' ');
|
|
List<string> argumentsList = new List<string>();
|
|
|
|
for (int i = 0; i < argumentsSplit.Length; i++)
|
|
{
|
|
if (argumentsSplit[i].Contains('"') && !argumentsSplit[i].EndsWith('"'))
|
|
{
|
|
StringBuilder quoteBuilder = new StringBuilder();
|
|
do
|
|
{
|
|
quoteBuilder.Append(' ');
|
|
quoteBuilder.Append(argumentsSplit[i]);
|
|
i++;
|
|
if (i >= argumentsSplit.Length)
|
|
{
|
|
throw new ArgumentException("Argument is missing terminating \'\"\'");
|
|
}
|
|
|
|
} while (!argumentsSplit[i].Contains('"'));
|
|
quoteBuilder.Append(' ');
|
|
quoteBuilder.Append(argumentsSplit[i]);
|
|
argumentsList.Add(quoteBuilder.ToString().Trim());
|
|
}
|
|
else
|
|
{
|
|
argumentsList.Add(argumentsSplit[i]);
|
|
}
|
|
}
|
|
arguments = argumentsList.ToArray();
|
|
}
|
|
if (!commands.ContainsKey(command)) throw new ArgumentException("Command not found.");
|
|
commands[command].Run(arguments);
|
|
}
|
|
}
|
|
}
|