| | | 1 | | namespace Envilder.Application; |
| | | 2 | | |
| | | 3 | | using Envilder.Domain; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using System.Text.Json.Serialization; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Parses a JSON map file into a <see cref="ParsedMapFile"/> containing |
| | | 10 | | /// provider configuration (<c>$config</c>) and environment variable mappings. |
| | | 11 | | /// </summary> |
| | | 12 | | public class MapFileParser |
| | | 13 | | { |
| | | 14 | | private const string ConfigKey = "$config"; |
| | | 15 | | |
| | 1 | 16 | | private static readonly JsonSerializerOptions SerializerOptions = new() |
| | 1 | 17 | | { |
| | 1 | 18 | | PropertyNameCaseInsensitive = true, |
| | 1 | 19 | | Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }, |
| | 1 | 20 | | }; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Parses raw JSON into a <see cref="ParsedMapFile"/>. |
| | | 24 | | /// The optional <c>$config</c> object is extracted as <see cref="MapFileConfig"/>; |
| | | 25 | | /// all other top-level string properties become secret mappings. |
| | | 26 | | /// </summary> |
| | | 27 | | /// <param name="json">Raw JSON content of the map file.</param> |
| | | 28 | | /// <returns>A <see cref="ParsedMapFile"/> ready for secret resolution.</returns> |
| | | 29 | | public ParsedMapFile Parse(string json) |
| | | 30 | | { |
| | 1 | 31 | | using var document = JsonDocument.Parse(json); |
| | 1 | 32 | | var mappings = new Dictionary<string, string>(); |
| | 1 | 33 | | var config = new MapFileConfig(); |
| | | 34 | | |
| | 1 | 35 | | foreach (var property in document.RootElement.EnumerateObject()) |
| | | 36 | | { |
| | 1 | 37 | | if (property.Name == ConfigKey) |
| | | 38 | | { |
| | 1 | 39 | | if (property.Value.ValueKind == JsonValueKind.Object) |
| | | 40 | | { |
| | 1 | 41 | | config = JsonSerializer.Deserialize<MapFileConfig>(property.Value.GetRawText(), SerializerOptions) |
| | 1 | 42 | | ?? new(); |
| | | 43 | | } |
| | | 44 | | |
| | 1 | 45 | | continue; |
| | | 46 | | } |
| | | 47 | | |
| | 1 | 48 | | if (property.Value.ValueKind != JsonValueKind.String) |
| | | 49 | | { |
| | | 50 | | continue; |
| | | 51 | | } |
| | | 52 | | |
| | 1 | 53 | | mappings[property.Name] = property.Value.GetString()!; |
| | | 54 | | } |
| | | 55 | | |
| | 1 | 56 | | return new(config, mappings); |
| | 1 | 57 | | } |
| | | 58 | | } |