summaryrefslogtreecommitdiff
path: root/src/Task/FileHandlers/ArmParametersFileHandler.cs
blob: 7c2148f4023318c4f27b322dc36f5f35f196f600 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace AggregateConfigBuildTask.FileHandlers
{
    /// <inheritdoc/>
    public class ArmParametersFileHandler : IFileHandler
    {
        private readonly IFileSystem fileSystem;

        private readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions { WriteIndented = true };

        internal ArmParametersFileHandler(IFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        /// <inheritdoc/>
        public async ValueTask<JsonElement> ReadInput(string inputPath)
        {
            using (var stream = fileSystem.OpenRead(inputPath))
            using (var jsonDoc = await JsonDocument.ParseAsync(stream).ConfigureAwait(false))
            {
                if (jsonDoc.RootElement.TryGetProperty("parameters", out JsonElement parameters))
                {
                    var modifiedParameters = new JsonObject();

                    foreach (var parameter in parameters.EnumerateObject())
                    {
                        if (parameter.Value.ValueKind == JsonValueKind.Object)
                        {
                            var paramObject = ConvertElementToNode(parameter.Value).AsObject();

                            // If the top-level object contains the "value" key, return the value
                            if (paramObject.ContainsKey("value"))
                            {
                                modifiedParameters[parameter.Name] = paramObject["value"]?.DeepClone();
                            }
                        }
                    }

                    var modifiedJson = modifiedParameters.ToJsonString();
                    return JsonSerializer.Deserialize<JsonElement>(modifiedJson);
                }

                return jsonDoc.RootElement.Clone();
            }
        }

        /// <inheritdoc/>
        public void WriteOutput(JsonElement? mergedData, string outputPath)
        {
            if (mergedData.HasValue && mergedData.Value.ValueKind == JsonValueKind.Object)
            {
                var parameters = new Dictionary<string, object>(StringComparer.Ordinal);

                foreach (var kvp in mergedData.Value.EnumerateObject())
                {
                    string type = GetParameterType(kvp.Value);

                    parameters[kvp.Name] = new Dictionary<string, object>(StringComparer.Ordinal)
                    {
                        ["type"] = type,
                        ["value"] = kvp.Value
                    };
                }

                // ARM template structure
                var armTemplate = new Dictionary<string, object>(StringComparer.Ordinal)
                {
                    ["$schema"] = "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
                    ["contentVersion"] = "1.0.0.0",
                    ["parameters"] = parameters
                };
                var jsonContent = JsonSerializer.Serialize(armTemplate, jsonOptions);
                fileSystem.WriteAllText(outputPath, jsonContent);
            }
            else
            {
                throw new InvalidOperationException("mergedData is either null or not a valid JSON object.");
            }
        }

        /// <summary>
        /// Determines the parameter type for a given JsonElement value, based on Azure ARM template supported types.
        /// </summary>
        /// <param name="value">The JsonElement value to evaluate.</param>
        /// <returns>A string representing the ARM template parameter type.</returns>
        /// <exception cref="ArgumentException">When a Json type cannot be mapped to an ARM template type</exception>
        private static string GetParameterType(JsonElement value)
        {
            switch (value.ValueKind)
            {
                case JsonValueKind.String:
                    return "string";

                case JsonValueKind.Number:
                    return "int";

                case JsonValueKind.True:
                case JsonValueKind.False:
                    return "bool";

                case JsonValueKind.Array:
                    return "array";

                case JsonValueKind.Object:
                    return "object";

                default:
                    throw new ArgumentException("Unsupported type for ARM template parameters.", nameof(value));
            }
        }

        private static JsonNode ConvertElementToNode(JsonElement element)
        {
            // Use GetRawText to get the JSON string representation of the JsonElement
            var jsonString = element.GetRawText();

            // Parse the string into a JsonNode
            return JsonNode.Parse(jsonString);
        }
    }
}