-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathRuntimeConfigParser.cs
169 lines (146 loc) · 5.49 KB
/
RuntimeConfigParser.cs
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Reflection.Metadata;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class RuntimeConfigParserTask : Task
{
/// <summary>
/// The path to runtimeconfig.json file.
/// </summary>
[Required]
public string RuntimeConfigFile { get; set; } = "";
/// <summary>
/// The path to the output binary file.
/// </summary>
[Required]
public string OutputFile { get; set; } = "";
/// <summary>
/// List of properties reserved for the host.
/// </summary>
public ITaskItem[] RuntimeConfigReservedProperties { get; set; } = Array.Empty<ITaskItem>();
public override bool Execute()
{
if (string.IsNullOrEmpty(RuntimeConfigFile))
{
Log.LogError($"'{nameof(RuntimeConfigFile)}' is required.");
}
if (string.IsNullOrEmpty(OutputFile))
{
Log.LogError($"'{nameof(OutputFile)}' is required.");
}
Dictionary<string, string> configProperties = ConvertInputToDictionary(RuntimeConfigFile);
if (RuntimeConfigReservedProperties.Length != 0)
{
CheckDuplicateProperties(configProperties, RuntimeConfigReservedProperties);
}
var blobBuilder = new BlobBuilder();
ConvertDictionaryToBlob(configProperties, blobBuilder);
Directory.CreateDirectory(Path.GetDirectoryName(OutputFile!)!);
using var stream = File.OpenWrite(OutputFile);
blobBuilder.WriteContentTo(stream);
return !Log.HasLoggedErrors;
}
/// Reads a json file from the given path and extracts the "configProperties" key (assumed to be a string to string dictionary)
private Dictionary<string, string> ConvertInputToDictionary(string inputFilePath)
{
var options = new JsonSerializerOptions {
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
Converters =
{
new StringConverter()
}
};
var jsonString = File.ReadAllText(inputFilePath);
var parsedJson = JsonSerializer.Deserialize<Root>(jsonString, options);
if (parsedJson == null)
{
throw new ArgumentException("Wasn't able to parse the json file successfully.");
}
if (parsedJson.RuntimeOptions == null)
{
throw new ArgumentException("Key runtimeOptions wasn't found in the json file.");
}
if (parsedJson.RuntimeOptions.ConfigProperties == null)
{
throw new ArgumentException("Key runtimeOptions->configProperties wasn't found in the json file.");
}
return parsedJson.RuntimeOptions.ConfigProperties;
}
/// Just write the dictionary out to a blob as a count followed by
/// a length-prefixed UTF8 encoding of each key and value
private void ConvertDictionaryToBlob(IReadOnlyDictionary<string, string> properties, BlobBuilder builder)
{
int count = properties.Count;
builder.WriteCompressedInteger(count);
foreach (var kvp in properties)
{
builder.WriteSerializedString(kvp.Key);
builder.WriteSerializedString(kvp.Value);
}
}
private void CheckDuplicateProperties(IReadOnlyDictionary<string, string> properties, ITaskItem[] keys)
{
foreach (var key in keys)
{
if (properties.ContainsKey(key.ItemSpec))
{
throw new ArgumentException($"Property '{key}' can't be set by the user!");
}
}
}
}
public class RuntimeOption
{
// the configProperties key
[JsonPropertyName("configProperties")]
public Dictionary<string, string> ConfigProperties { get; set; } = new Dictionary<string, string>();
// everything other than configProperties
[JsonExtensionData]
public Dictionary<string, object> ExtensionDataSub { get; set; } = new Dictionary<string, object>();
}
public class Root
{
// the runtimeOptions key
[JsonPropertyName("runtimeOptions")]
public RuntimeOption RuntimeOptions { get; set; } = new RuntimeOption();
// everything other than runtimeOptions
[JsonExtensionData]
public Dictionary<string, object> ExtensionDataRoot { get; set; } = new Dictionary<string, object>();
}
public class StringConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.Number:
var stringValueInt = reader.GetInt32();
return stringValueInt.ToString();
case JsonTokenType.True:
return "true";
case JsonTokenType.False:
return "false";
case JsonTokenType.String:
var stringValue = reader.GetString();
if (stringValue != null)
{
return stringValue;
}
break;
default:
throw new System.Text.Json.JsonException();
}
throw new System.Text.Json.JsonException();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}