-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
336 lines (289 loc) · 12 KB
/
Program.cs
File metadata and controls
336 lines (289 loc) · 12 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
using System.Net.Http;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
var exitCode = await MimeTypeSyncTool.RunAsync(args);
return exitCode;
internal static class MimeTypeSyncTool
{
private static readonly string[] DefaultSources =
{
"https://raw.githubusercontent.com/jshttp/mime-db/master/db.json",
"https://raw.githubusercontent.com/apache/httpd/trunk/docs/conf/mime.types"
};
public static async Task<int> RunAsync(string[] args)
{
try
{
var options = SyncOptions.Parse(args);
var remoteData = await LoadRemoteAsync(options.Sources);
var existing = LoadExisting(options.OutputPath);
var merged = Merge(remoteData, existing, options);
WriteOutput(options.OutputPath, merged);
Console.WriteLine($"Updated {options.OutputPath} with {merged.Count.ToString("N0", CultureInfo.InvariantCulture)} entries (remote: {remoteData.Count.ToString("N0", CultureInfo.InvariantCulture)}, existing: {existing.Count.ToString("N0", CultureInfo.InvariantCulture)}).");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
return 1;
}
}
private static async Task<Dictionary<string, string>> LoadRemoteAsync(IReadOnlyList<string> sources)
{
if (sources.Count == 0)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
using var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("ManagedCode.MimeTypes.Sync/1.0");
var aggregate = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var source in sources)
{
var data = await LoadRawDataAsync(client, source);
var parsed = ParseRemoteData(source, data);
foreach (var kvp in parsed)
{
aggregate[kvp.Key] = kvp.Value;
}
}
return aggregate;
}
private static async Task<byte[]> LoadRawDataAsync(HttpClient client, string source)
{
if (Uri.TryCreate(source, UriKind.Absolute, out var uri) && uri.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
return await client.GetByteArrayAsync(uri);
}
return await File.ReadAllBytesAsync(source);
}
private static Dictionary<string, string> ParseRemoteData(string source, byte[] data)
{
var firstNonWhitespace = data.FirstOrDefault(static b => !char.IsWhiteSpace((char)b));
if (firstNonWhitespace == '{' || firstNonWhitespace == '[')
{
return ParseJsonSource(source, data);
}
return ParseMimeTypesListing(source, data);
}
private static Dictionary<string, string> ParseJsonSource(string source, byte[] data)
{
using var document = JsonDocument.Parse(data);
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (document.RootElement.ValueKind == JsonValueKind.Object)
{
foreach (var property in document.RootElement.EnumerateObject())
{
switch (property.Value.ValueKind)
{
case JsonValueKind.Object when property.Value.TryGetProperty("extensions", out var extensionsElement):
AddExtensions(dictionary, property.Name, extensionsElement);
break;
case JsonValueKind.String:
AddExtension(dictionary, property.Name, property.Value.GetString());
break;
case JsonValueKind.Array:
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String)
{
AddExtension(dictionary, item.GetString(), property.Name);
}
}
break;
}
}
}
else if (document.RootElement.ValueKind == JsonValueKind.Array)
{
foreach (var element in document.RootElement.EnumerateArray())
{
if (element.ValueKind == JsonValueKind.Object &&
element.TryGetProperty("extension", out var extensionProperty) &&
element.TryGetProperty("mime", out var mimeProperty))
{
AddExtension(dictionary, extensionProperty.GetString(), mimeProperty.GetString());
}
}
}
else
{
Console.WriteLine($"Warning: Unsupported JSON format from {source}." );
}
return dictionary;
}
private static Dictionary<string, string> ParseMimeTypesListing(string source, byte[] data)
{
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
using var reader = new StreamReader(new MemoryStream(data), Encoding.UTF8, true);
while (reader.ReadLine() is { } line)
{
line = line.Trim();
if (line.Length == 0 || line.StartsWith('#'))
{
continue;
}
var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length < 2)
{
continue;
}
var mime = parts[0];
for (var i = 1; i < parts.Length; i++)
{
AddExtension(dictionary, parts[i], mime);
}
}
if (dictionary.Count == 0)
{
Console.WriteLine($"Warning: No MIME entries parsed from {source}." );
}
return dictionary;
}
private static void AddExtensions(Dictionary<string, string> dictionary, string mime, JsonElement extensionsElement)
{
foreach (var extension in extensionsElement.EnumerateArray())
{
if (extension.ValueKind == JsonValueKind.String)
{
AddExtension(dictionary, extension.GetString(), mime);
}
}
}
private static void AddExtension(Dictionary<string, string> dictionary, string? extension, string? mime)
{
var normalized = NormalizeExtension(extension);
if (string.IsNullOrEmpty(normalized) || string.IsNullOrWhiteSpace(mime))
{
return;
}
dictionary[normalized] = mime!;
}
private static Dictionary<string, string> LoadExisting(string outputPath)
{
if (!File.Exists(outputPath))
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
using var document = JsonDocument.Parse(File.ReadAllText(outputPath));
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var property in document.RootElement.EnumerateObject())
{
var normalized = NormalizeExtension(property.Name);
var value = property.Value.GetString();
if (string.IsNullOrEmpty(normalized) || string.IsNullOrEmpty(value))
{
continue;
}
dictionary[normalized] = value;
}
return dictionary;
}
private static Dictionary<string, string> Merge(Dictionary<string, string> remote, Dictionary<string, string> existing, SyncOptions options)
{
var result = new Dictionary<string, string>(remote, StringComparer.OrdinalIgnoreCase);
foreach (var kvp in existing)
{
if (options.PreferRemote)
{
result.TryAdd(kvp.Key, kvp.Value);
}
else
{
result[kvp.Key] = kvp.Value;
}
}
foreach (var kvp in CustomMappings())
{
result[kvp.Key] = kvp.Value;
}
return result;
}
private static IEnumerable<KeyValuePair<string, string>> CustomMappings()
{
yield return new KeyValuePair<string, string>("tar.gz", "application/gzip");
yield return new KeyValuePair<string, string>("tar.bz2", "application/x-bzip2");
yield return new KeyValuePair<string, string>("tar.xz", "application/x-xz");
yield return new KeyValuePair<string, string>("tar.zst", "application/zstd");
yield return new KeyValuePair<string, string>("d.ts", "application/typescript");
yield return new KeyValuePair<string, string>("cjs", "application/node");
yield return new KeyValuePair<string, string>("mjs", "text/javascript");
yield return new KeyValuePair<string, string>("wasm", "application/wasm");
yield return new KeyValuePair<string, string>("heic", "image/heic");
yield return new KeyValuePair<string, string>("heif", "image/heif");
yield return new KeyValuePair<string, string>("ics", "text/calendar");
yield return new KeyValuePair<string, string>("ps1", "application/x-powershell");
yield return new KeyValuePair<string, string>("appx", "application/vnd.ms-appx");
}
private static void WriteOutput(string outputPath, Dictionary<string, string> data)
{
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
using var stream = File.Create(outputPath);
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions
{
Indented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
writer.WriteStartObject();
foreach (var kvp in data.OrderBy(static x => x.Key, StringComparer.OrdinalIgnoreCase))
{
writer.WriteString(kvp.Key, kvp.Value);
}
writer.WriteEndObject();
}
private static string NormalizeExtension(string? extension)
{
if (string.IsNullOrWhiteSpace(extension))
{
return string.Empty;
}
return extension.Trim().Trim('.').ToLowerInvariant();
}
private sealed record SyncOptions(IReadOnlyList<string> Sources, string OutputPath, bool PreferRemote)
{
public static SyncOptions Parse(string[] args)
{
var sources = new List<string>(DefaultSources);
string? output = null;
bool preferRemote = false;
var customSources = false;
for (var i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--source" when i + 1 < args.Length:
if (!customSources)
{
sources.Clear();
customSources = true;
}
foreach (var value in args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
sources.Add(value);
}
break;
case "--add-source" when i + 1 < args.Length:
foreach (var value in args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
sources.Add(value);
}
break;
case "--reset-sources":
sources.Clear();
customSources = true;
break;
case "--output" when i + 1 < args.Length:
output = args[++i];
break;
case "--prefer-remote":
preferRemote = true;
break;
}
}
output ??= Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "ManagedCode.MimeTypes", "mimeTypes.json"));
return new SyncOptions(sources, output, preferRemote);
}
}
}