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