5dplomacy/MultiversalDiplomacy/CommandLine/ReplOptions.cs

85 lines
2.8 KiB
C#
Raw Normal View History

2024-08-16 20:33:13 +00:00
using CommandLine;
2024-08-16 21:39:13 +00:00
using MultiversalDiplomacy.Script;
2024-08-16 20:33:13 +00:00
namespace MultiversalDiplomacy.CommandLine;
[Verb("repl", HelpText = "Begin an interactive 5dplomacy session.")]
public class ReplOptions
{
2024-08-16 21:39:13 +00:00
[Option('i', "input", HelpText = "Begin the repl session by executing the commands in this file.")]
public string? InputFile { get; set; }
[Option('o', "output", HelpText = "Echo the repl session to this file. Specify a directory to autogenerate a filename.")]
public string? OutputFile { get; set; }
2024-08-16 20:33:13 +00:00
public static void Execute(ReplOptions args)
{
2024-08-16 21:39:13 +00:00
IEnumerable<string>? inputFileLines = null;
if (args.InputFile is not null) {
var fullPath = Path.GetFullPath(args.InputFile);
inputFileLines = File.ReadAllLines(fullPath);
Console.WriteLine($"Reading from {fullPath}");
}
// Create a writer to the output file, if specified.
StreamWriter? outputWriter = null;
if (args.OutputFile is not null)
{
string fullPath = Path.GetFullPath(args.OutputFile);
string outputPath = Directory.Exists(fullPath)
? Path.Combine(fullPath, $"{DateTime.UtcNow:yyyyMMddHHmmss}.log")
: fullPath;
Console.WriteLine($"Echoing to {outputPath}");
outputWriter = File.CreateText(outputPath);
}
IEnumerable<string?> GetInputs()
{
foreach (string line in inputFileLines ?? [])
{
var trimmed = line.Trim();
// File inputs weren't echoed to the terminal so they need to be echoed here
Console.WriteLine($"{trimmed}");
yield return trimmed;
}
string? input;
do
{
input = Console.ReadLine();
yield return input;
}
while (input is not null);
// The last null is returned because an EOF means we should quit the repl.
}
2024-08-28 21:10:41 +00:00
IScriptHandler? handler = new ReplScriptHandler(Console.WriteLine);
2024-08-16 21:39:13 +00:00
Console.Write(handler.Prompt);
foreach (string? nextInput in GetInputs())
{
// Handle quitting directly.
if (nextInput is null || nextInput == "quit" || nextInput == "exit")
{
break;
}
string input = nextInput.Trim();
outputWriter?.WriteLine(input);
outputWriter?.Flush();
// Delegate all other command parsing to the handler.
handler = handler.HandleInput(input);
// Quit if the handler ends processing, otherwise prompt for the next command.
if (handler is null)
{
break;
}
Console.Write(handler.Prompt);
}
Console.WriteLine("exiting");
2024-08-16 20:33:13 +00:00
}
}