81 lines
2.9 KiB
C#
81 lines
2.9 KiB
C#
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
|
|
{
|
|
internal class GenerationCommand : Command
|
|
{
|
|
const string NAME = "generate";
|
|
const string DESC = "Generate a .resx file.";
|
|
|
|
public GenerationCommand() : base(NAME, DESC)
|
|
{
|
|
Argument<FileInfo> destArg = new Argument<FileInfo>("destination", "The destination path to store this file. If no extension is given, .resx will automatically be concatenated.");
|
|
Add(destArg);
|
|
|
|
Option<FileInfo?> fromOpt = new Option<FileInfo?>("--from", "Generates a .resx file from the given file.");
|
|
Add(fromOpt);
|
|
|
|
this.SetHandler(async (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);
|
|
}
|
|
}
|
|
}, destArg, fromOpt);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
} |