jtr/DevDisciples.Json.Tools.CLI/IOHandler.cs
2024-09-15 17:23:27 +02:00

74 lines
2.3 KiB
C#

using TextCopy;
namespace DevDisciples.Json.Tools.CLI;
public static class IOHandler
{
public static async Task<string> HandleInput(InputOptions input, string? inputArgument, FileInfo? inputFile)
{
string json;
switch (input)
{
case InputOptions.s:
case InputOptions.std:
case InputOptions.stdin:
json = inputArgument ?? string.Empty;
break;
case InputOptions.c:
case InputOptions.clip:
case InputOptions.clipboard:
json = await ClipboardService.GetTextAsync() ?? string.Empty;
break;
case InputOptions.f:
case InputOptions.file:
if (inputFile is null)
throw new ArgumentException("Input file was not specified.");
if (!inputFile.Exists)
throw new FileNotFoundException($"File {inputFile.FullName} does not exist.");
json = await File.ReadAllTextAsync(inputFile.FullName);
break;
default:
throw new Exception($"Input type '{input}' is not supported.");
}
return json.Trim();
}
public static async Task HandleOutput(OutputOptions output, FileInfo? outputFile, string result)
{
switch (output)
{
case OutputOptions.s:
case OutputOptions.std:
case OutputOptions.stdout:
Console.WriteLine(result);
break;
case OutputOptions.c:
case OutputOptions.clip:
case OutputOptions.clipboard:
await ClipboardService.SetTextAsync(result);
break;
case OutputOptions.f:
case OutputOptions.file:
if (outputFile is null)
throw new ArgumentException("Output file was not specified.");
if (outputFile.Exists)
throw new Exception($"File {outputFile.FullName} already exists.");
await File.WriteAllTextAsync(outputFile.FullName, result);
break;
default:
throw new Exception($"Output type '{output}' is not supported.");
}
}
}