dotnetresxutils/DotNetResxUtils/Commands/GenerationCommand.cs

84 lines
2.9 KiB
C#
Raw Normal View History

2022-05-16 06:21:51 +00:00
using System.Collections.Generic;
using System.IO;
using System.CommandLine;
using System.Text.Json;
using System.Threading.Tasks;
using System.Resources.NetStandard;
namespace DotNetResxUtils.Commands
{
2022-05-16 07:25:54 +00:00
internal class GenerationCommand : Command
2022-05-16 06:21:51 +00:00
{
const string NAME = "generate";
const string DESC = "Generate a .resx file.";
2022-05-16 07:25:54 +00:00
public GenerationCommand() : base(NAME, DESC)
2022-05-16 06:21:51 +00:00
{
Option<FileInfo?> fromOpt = new Option<FileInfo?>("--from", "Generates a .resx file from the given file.");
Argument<FileInfo> destArg = new Argument<FileInfo>("destination", "The destination path to store this file. If no extension is given, .resx will automatically be concatenated.");
2022-05-16 07:25:54 +00:00
this.AddOption(fromOpt);
this.AddArgument(destArg);
2022-05-16 06:21:51 +00:00
2022-05-16 07:25:54 +00:00
this.SetHandler<FileInfo, FileInfo?>(CommandHandler, destArg, fromOpt);
2022-05-16 06:21:51 +00:00
}
private async void CommandHandler(FileInfo to, FileInfo? from)
{
IDictionary<string, string> flattened = new Dictionary<string, string>();
if (from != null)
{
flattened = await FlattenJson(from);
}
using (ResXResourceWriter resxWriter = new ResXResourceWriter(to.FullName))
{
foreach (KeyValuePair<string, string> keyVal in flattened)
{
resxWriter.AddResource(keyVal.Key, keyVal.Value);
}
}
}
private async Task<IDictionary<string, string>> FlattenJson(FileInfo jsonFile)
{
JsonElement jsonObj;
using (FileStream readStream = jsonFile.OpenRead())
{
jsonObj = await JsonSerializer.DeserializeAsync<JsonElement>(readStream);
}
Dictionary<string, string> result = new Dictionary<string, string>();
FlattenJsonElement(result, jsonObj, "");
return result;
}
private void FlattenJsonElement(IDictionary<string, string> flattened, JsonElement jsonElement, string namepath)
{
if (jsonElement.ValueKind == JsonValueKind.Array)
{
int itemIndex = 0;
foreach (JsonElement item in jsonElement.EnumerateArray())
{
FlattenJsonElement(flattened, item, namepath + $"[{itemIndex}]");
}
}
else if (jsonElement.ValueKind == JsonValueKind.Object)
{
foreach (JsonProperty item in jsonElement.EnumerateObject())
{
FlattenJsonElement(flattened, item.Value, namepath + $".{item.Name}");
}
}
else
{
string? stored = jsonElement.GetString();
if (stored != null)
{
flattened[namepath] = stored;
}
}
}
}
}