This repository has been archived by the owner on Jul 16, 2023. It is now read-only.
/
TemplateClassGenerator.cs
180 lines (154 loc) · 5.88 KB
/
TemplateClassGenerator.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
170
171
172
173
174
175
176
177
178
179
180
using System.Text;
using System;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using MiniRazor.CodeGen.Utils.Extensions;
namespace MiniRazor.CodeGen;
[Generator]
public partial class TemplateClassGenerator : ISourceGenerator
{
private static readonly string GeneratorVersion =
typeof(TemplateClassGenerator)
.Assembly
.GetName()
.Version
.ToString(3);
private static string? TryGetModelTypeName(string code, string className) =>
Regex
.Match(
code,
$@"\s*{Regex.Escape(className)}\s*:\s*MiniRazor\.TemplateBase<(.+)>",
RegexOptions.Multiline,
TimeSpan.FromSeconds(1)
)
.Groups[1]
.Value
.NullIfWhiteSpace();
private static string? TryGetNamespace(string code) =>
Regex
.Match(
code,
@"namespace (\S+)",
RegexOptions.Multiline,
TimeSpan.FromSeconds(1)
)
.Groups[1]
.Value
.NullIfWhiteSpace();
// Checksum directive contains a file name which might not match the hint name
// of the generated file. This can cause issues where the PDB file might reference
// a compilation unit that doesn't actually exist. Also, the directive isn't very
// useful to us anyway so it's best to just remove it.
private static string StripChecksumDirectives(string code) =>
Regex.Replace(
code,
@"^\s*#pragma checksum\s+.+$", "",
RegexOptions.Multiline, TimeSpan.FromSeconds(1)
);
// Avoid nullability warnings in the generated code
private static string StripNullableDirectives(string code) =>
Regex.Replace(
code,
@"^\s*#nullable\s+(restore|disable)\s*$",
"",
RegexOptions.Multiline,
TimeSpan.FromSeconds(1)
);
private void ProcessFile(
GeneratorExecutionContext context,
string filePath,
string accessModifier,
string content)
{
// Generate class name from file name
var className = SanitizeSymbolName(
Path.GetFileNameWithoutExtension(filePath)
);
var code = Razor.Transpile(content, className, accessModifier);
// Get model type from the template's base class
var modelTypeName = TryGetModelTypeName(code, className) ?? "dynamic";
var ns = TryGetNamespace(code);
// Remove junk generated by Razor compiler
code = StripChecksumDirectives(code);
code = StripNullableDirectives(code).Insert(0, "#nullable disable" + Environment.NewLine);
// Add documentation to the class
code = code.Insert(code.IndexOf($"{accessModifier} partial class", StringComparison.Ordinal), $@"
/// <summary>Template: {filePath}</summary>
/// <remarks>Generated by MiniRazor v{GeneratorVersion} on {DateTimeOffset.Now}.</remarks>
");
// Extend the template with some additional code
code = code.Insert(code.IndexOf("public async override", StringComparison.Ordinal), $@"
/// <summary>Renders the template using the specified writer.</summary>
public static async global::System.Threading.Tasks.Task RenderAsync(global::System.IO.TextWriter output, {modelTypeName} model, global::System.Threading.CancellationToken cancellationToken = default)
{{
var template = new {className}();
template.Output = output;
template.Model = model;
template.CancellationToken = cancellationToken;
await template.ExecuteAsync().ConfigureAwait(false);
}}
/// <summary>Renders the template to a string.</summary>
public static async global::System.Threading.Tasks.Task<string> RenderAsync({modelTypeName} model, global::System.Threading.CancellationToken cancellationToken = default)
{{
using (var output = new global::System.IO.StringWriter())
{{
await RenderAsync(output, model, cancellationToken).ConfigureAwait(false);
return output.ToString();
}}
}}
");
var hintName = !string.IsNullOrWhiteSpace(ns)
? $"{ns}.{className}.g.cs"
: className;
context.AddSource(hintName, code);
}
/// <inheritdoc />
public void Execute(GeneratorExecutionContext context)
{
foreach (var file in context.AdditionalFiles)
{
var isRazorTemplate = string.Equals(
context
.AnalyzerConfigOptions
.GetOptions(file)
.TryGetAdditionalFileMetadataValue("IsRazorTemplate"),
"true",
StringComparison.OrdinalIgnoreCase
);
if (!isRazorTemplate)
continue;
var accessModifier = context
.AnalyzerConfigOptions
.GetOptions(file)
.TryGetAdditionalFileMetadataValue("AccessModifier") ?? "internal";
var content = file.GetText(context.CancellationToken)?.ToString();
if (string.IsNullOrWhiteSpace(content))
continue;
ProcessFile(context, file.Path, accessModifier, content);
}
}
/// <inheritdoc />
public void Initialize(GeneratorInitializationContext context)
{
}
}
public partial class TemplateClassGenerator
{
private static string SanitizeSymbolName(string identifier)
{
var buffer = new StringBuilder(identifier);
// Must start with a letter or an underscore
if (buffer.Length > 0 && buffer[0] != '_' && !char.IsLetter(buffer[0]))
{
buffer.Insert(0, '_');
}
// Replace all other prohibited characters with underscores
for (var i = 0; i < buffer.Length; i++)
{
if (!char.IsLetterOrDigit(buffer[i]))
buffer[i] = '_';
}
return buffer.ToString();
}
}