Skip to content

Instantly share code, notes, and snippets.

@AtomicBlom
Created October 11, 2018 08:52
Show Gist options
  • Save AtomicBlom/d06ad6d83076794081f3dc4450199ada to your computer and use it in GitHub Desktop.
Save AtomicBlom/d06ad6d83076794081f3dc4450199ada to your computer and use it in GitHub Desktop.
A simple REPL loop for Brigadier.NET
using System;
using System.Threading.Tasks;
using Brigadier.NET;
using Brigadier.NET.Builder;
using Brigadier.NET.Exceptions;
using static Brigadier.NET.Arguments;
namespace TestBrigadier
{
class Program
{
static async Task Main(string[] args)
{
var dispatcher = new CommandDispatcher<CommandSourceStack>();
dispatcher.Register(l =>
l.Literal("foo")
.Then(a =>
a.Argument("bar", Integer())
.Executes(c => {
Console.WriteLine("Bar is " + GetInteger(c, "bar"));
return 1;
})
)
.Executes(c => {
Console.WriteLine("Called foo with no arguments");
return 1;
})
);
string input = string.Empty;
Console.Write("> ");
while (true)
{
var key = Console.ReadKey(intercept: true);
switch (key.Key)
{
case ConsoleKey.Escape:
return;
case ConsoleKey.Backspace when input.Length > 0:
input = input.Substring(0, input.Length - 1);
Console.Write(key.KeyChar);
Console.Write(' ');
Console.Write(key.KeyChar);
break;
case ConsoleKey.Tab:
{
var parseResults = dispatcher.Parse(input, new CommandSourceStack());
var results = await dispatcher.GetCompletionSuggestions(parseResults);
Console.WriteLine();
foreach (var suggestion in results.List)
{
Console.Write(new string(' ', parseResults.Reader.Cursor + 2));
Console.WriteLine(suggestion.Text);
}
Console.Write("> " + input);
break;
}
case ConsoleKey.Enter:
Console.WriteLine();
try
{
dispatcher.Execute(input, new CommandSourceStack());
}
catch (CommandSyntaxException e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(new string(' ', e.Cursor));
Console.Write("^ ");
Console.WriteLine(e.Message);
Console.ForegroundColor = ConsoleColor.White;
}
Console.Write("> ");
input = string.Empty;
break;
default:
{
if (!char.IsControl(key.KeyChar))
{
input += key.KeyChar;
Console.Write(key.KeyChar);
}
break;
}
}
}
}
}
class CommandSourceStack
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment