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) { Option fromOpt = new Option("--from", "Generates a .resx file from the given file."); Argument destArg = new Argument("destination", "The destination path to store this file. If no extension is given, .resx will automatically be concatenated."); this.AddOption(fromOpt); this.AddArgument(destArg); this.SetHandler(CommandHandler, destArg, fromOpt); } private async void CommandHandler(FileInfo to, FileInfo? from) { IDictionary flattened = new Dictionary(); if (from != null) { flattened = await FlattenJson(from); } using (ResXResourceWriter resxWriter = new ResXResourceWriter(to.FullName)) { foreach (KeyValuePair keyVal in flattened) { resxWriter.AddResource(keyVal.Key, keyVal.Value); } } } private async Task> FlattenJson(FileInfo jsonFile) { JsonElement jsonObj; using (FileStream readStream = jsonFile.OpenRead()) { jsonObj = await JsonSerializer.DeserializeAsync(readStream); } Dictionary result = new Dictionary(); FlattenJsonElement(result, jsonObj, ""); return result; } private void FlattenJsonElement(IDictionary 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; } } } } }