-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMimeTypeSourceGenerator.cs
More file actions
150 lines (130 loc) · 4.5 KB
/
MimeTypeSourceGenerator.cs
File metadata and controls
150 lines (130 loc) · 4.5 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
using System;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace ManagedCode.MimeTypes.Generator;
[Generator]
public class MimeTypeSourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
#if DEBUG
if (!Debugger.IsAttached)
{
Debugger.Launch();
}
#endif
}
public void Execute(GeneratorExecutionContext context)
{
try
{
// Find the mimeTypes.json file
var mimeTypesPath = GetMimeTypesPath(context);
if (!File.Exists(mimeTypesPath))
{
context.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
"MIME001",
"MimeTypes.json not found",
"Could not find mimeTypes.json at {0}",
"MimeTypes",
DiagnosticSeverity.Error,
true),
Location.None,
mimeTypesPath));
return;
}
var mime = JObject.Parse(File.ReadAllText(mimeTypesPath));
var properties = mime.Properties().ToList();
context.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
"MIME002",
"MimeTypes loaded",
"Successfully loaded {0} mime types",
"MimeTypes",
DiagnosticSeverity.Info,
true),
Location.None,
properties.Count));
StringBuilder defineDictionaryBuilder = new();
StringBuilder propertyBuilder = new();
Dictionary<string, string> types = new Dictionary<string, string>();
foreach (var item in properties)
{
var extension = item.Name.Trim();
var mimeValue = item.Value.ToString()?.Trim() ?? string.Empty;
defineDictionaryBuilder.AppendLine($"RegisterMimeTypeInternal(\"{Escape(extension)}\", \"{Escape(mimeValue)}\");");
types[ParseKey(extension)] = mimeValue;
}
foreach (var item in types)
{
propertyBuilder.AppendLine($"public static string {item.Key} => \"{Escape(item.Value)}\";");
}
context.AddSource("MimeHelper.Properties.cs", SourceText.From(@$"
namespace ManagedCode.MimeTypes
{{
public static partial class MimeHelper
{{
static partial void Init()
{{
{defineDictionaryBuilder}
}}
{propertyBuilder}
}}
}}
", Encoding.UTF8));
}
catch (Exception ex)
{
context.ReportDiagnostic(Diagnostic.Create(
new DiagnosticDescriptor(
"MIME003",
"Generator Error",
"Error generating mime types: {0}",
"MimeTypes",
DiagnosticSeverity.Error,
true),
Location.None,
ex.ToString()));
}
}
private string GetMimeTypesPath(GeneratorExecutionContext context)
{
// Try to find mimeTypes.json in the project directory
var compilation = context.Compilation;
var projectDir = Path.GetDirectoryName(compilation.SyntaxTrees.First().FilePath);
var possiblePaths = new[]
{
// Try current directory
Path.Combine(Directory.GetCurrentDirectory(), "mimeTypes.json"),
// Try project directory
Path.Combine(projectDir ?? "", "mimeTypes.json"),
// Try one level up (solution directory)
Path.Combine(Directory.GetParent(projectDir ?? "")?.FullName ?? "", "mimeTypes.json"),
// Try in the Generator project
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mimeTypes.json")
};
return possiblePaths.FirstOrDefault(File.Exists) ?? possiblePaths[0];
}
private static string ParseKey(string key)
{
if (char.IsDigit(key[0]))
{
key = "_" + key;
}
key = key.Replace("-", "_").Replace('.', '_');
return key.ToUpperInvariant();
}
private static string Escape(string value)
{
return value
.Replace("\\", "\\\\")
.Replace("\"", "\\\"");
}
}