Skip to content

Commit

Permalink
Add JSON read from file
Browse files Browse the repository at this point in the history
  • Loading branch information
nRafinia committed Mar 18, 2023
1 parent ab369ba commit 8f8aeea
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions src/nHash/SubFeatures/Texts/JsonFeature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ public class JsonFeature: IFeature
{
private readonly Argument<string> _textArgument;
private readonly Option<JsonPrintType> _printType;
private readonly Option<string> _fileName;

public JsonFeature()
{
_textArgument = new Argument<string>("text", "JSON text for processing");
_textArgument = new Argument<string>("text",() => string.Empty, "JSON text for processing");
_printType = new Option<JsonPrintType>("--print", "Print pretty/Compact JSON representation");
_fileName = new Option<string>(name: "--file", description: "File name for read JSON from that");
}

public Command Command => GetFeatureCommand();
Expand All @@ -20,20 +22,44 @@ private Command GetFeatureCommand()
{
var command = new Command("json", "JSON tools")
{
_printType
_printType,
_fileName
};
command.AddArgument(_textArgument);
command.SetHandler(CalculateText, _textArgument, _printType);
command.SetHandler(CalculateText, _textArgument, _printType, _fileName);

return command;
}

private static void CalculateText(string text, JsonPrintType printType)
private static void CalculateText(string text, JsonPrintType printType, string fileName)
{
if (!string.IsNullOrWhiteSpace(text))
{
var jsonText = CalculateJsonText(text, printType);
Console.WriteLine(jsonText);
return;
}

if (!string.IsNullOrWhiteSpace(fileName))
{
if (!File.Exists(fileName))
{
Console.WriteLine($"File {fileName} does not exists!");
return;
}

var fileContent = File.ReadAllText(fileName);
var jsonText = CalculateJsonText(fileContent, printType);
Console.WriteLine(jsonText);
}
}

private static string CalculateJsonText(string text, JsonPrintType printType)
{
var prettyJson = new JsonTools();
var jsonText = printType == JsonPrintType.Pretty
? prettyJson.SetBeautiful(text)
: prettyJson.SetCompact(text);
Console.WriteLine(jsonText);
return jsonText;
}
}

0 comments on commit 8f8aeea

Please sign in to comment.