-
Notifications
You must be signed in to change notification settings - Fork 24
feat: replace T4 template with Roslyn source generator #234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -274,3 +274,4 @@ __pycache__/ | |
| # Cake - Uncomment if you are using it | ||
| # tools/ | ||
| KnownMimeTypes.cs | ||
| mime-db.json | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| using System.Text; | ||
|
|
||
| namespace MimeMapping.SourceGenerator | ||
| { | ||
| /// <summary> | ||
| /// Generates the KnownMimeTypes.cs source code from parsed MIME data | ||
| /// </summary> | ||
| internal static class CodeGenerator | ||
| { | ||
| public static string Generate(MimeDbData data) | ||
| { | ||
| var sb = new StringBuilder(); | ||
|
|
||
| // Header | ||
| sb.AppendLine("using System;"); | ||
| sb.AppendLine(); | ||
| sb.AppendLine("#nullable enable"); | ||
| sb.AppendLine(); | ||
| sb.AppendLine("namespace MimeMapping"); | ||
| sb.AppendLine("{"); | ||
|
|
||
| // Class documentation | ||
| sb.AppendLine(" ///<summary>"); | ||
| sb.AppendLine($" /// MIME type constants. Last updated on {data.GeneratedAt:s}Z. "); | ||
| sb.AppendLine($" /// Generated from the <a href=\"{data.SourceUrl}\">mime-db</a> source"); | ||
| sb.AppendLine(" ///</summary>"); | ||
| sb.AppendLine(" public static class KnownMimeTypes"); | ||
| sb.AppendLine(" {"); | ||
| sb.AppendLine(); | ||
|
|
||
| // Conflict resolution comments | ||
| foreach (var comment in data.ConflictComments) | ||
| { | ||
| sb.AppendLine($" {comment}"); | ||
| } | ||
|
|
||
| // Summary comments | ||
| sb.AppendLine(); | ||
| sb.AppendLine($" // Generated {data.MimeTypeToExtensions.Count} unique mime type values"); | ||
| sb.AppendLine($" // Generated {data.ExtensionToMimeType.Count} type key pairs"); | ||
| sb.AppendLine(); | ||
|
|
||
| // Source URL constant | ||
| sb.AppendLine(" ///<summary>The source URL of the mime-db data used to generate this file</summary>"); | ||
| sb.AppendLine($" internal const string MimeDbSourceUrl = \"{data.SourceUrl}\";"); | ||
| sb.AppendLine(); | ||
|
|
||
| // MIME type constants | ||
| foreach (var kv in data.ExtensionToMimeType) | ||
| { | ||
| var fieldName = NameUtilities.GetMimeFieldName(kv.Key); | ||
| sb.AppendLine($" ///<summary>{kv.Key}</summary>"); | ||
| sb.AppendLine($" public const string {fieldName} = \"{kv.Value}\";"); | ||
| } | ||
|
|
||
| // ALL_MIMETYPES lazy array | ||
| sb.AppendLine(" // List of all available mimetypes, used to build the dictionary"); | ||
| sb.AppendLine(" internal static readonly Lazy<string[]> ALL_MIMETYPES = new Lazy<string[]>(() => new [] {"); | ||
| foreach (var kv in data.ExtensionToMimeType) | ||
| { | ||
| var fieldName = NameUtilities.GetMimeFieldName(kv.Key); | ||
| sb.AppendLine($" {fieldName},"); | ||
| } | ||
| sb.AppendLine(" });"); | ||
| sb.AppendLine(); | ||
| sb.AppendLine(); | ||
|
|
||
| // FileExtensions nested class | ||
| sb.AppendLine(" ///<summary>File extensions</summary>"); | ||
| sb.AppendLine(" public static class FileExtensions"); | ||
| sb.AppendLine(" {"); | ||
| foreach (var kv in data.ExtensionToMimeType) | ||
| { | ||
| var fieldName = NameUtilities.GetExtensionFieldName(kv.Key); | ||
| sb.AppendLine($" ///<summary>{kv.Key}</summary>"); | ||
| sb.AppendLine($" public const string {fieldName} = \"{kv.Key}\";"); | ||
| } | ||
| sb.AppendLine(" }"); | ||
| sb.AppendLine(); | ||
|
|
||
| // ALL_EXTS lazy array | ||
| sb.AppendLine(" // List of all available extensions, used to build the dictionary"); | ||
| sb.AppendLine(" internal static readonly Lazy<string[]> ALL_EXTS = new Lazy<string[]>(() => new [] {"); | ||
| foreach (var kv in data.ExtensionToMimeType) | ||
| { | ||
| var fieldName = NameUtilities.GetExtensionFieldName(kv.Key); | ||
| sb.AppendLine($" FileExtensions.{fieldName},"); | ||
| } | ||
| sb.AppendLine(" });"); | ||
| sb.AppendLine(); | ||
| sb.AppendLine(); | ||
|
|
||
| // LookupType switch statement | ||
| GenerateLookupTypeMethod(sb, data); | ||
|
|
||
| // LookupMimeType switch statement | ||
| GenerateLookupMimeTypeMethod(sb, data); | ||
|
|
||
| // Close class and namespace | ||
| sb.AppendLine(" }"); | ||
| sb.AppendLine("}"); | ||
|
|
||
| return sb.ToString(); | ||
| } | ||
|
|
||
| private static void GenerateLookupTypeMethod(StringBuilder sb, MimeDbData data) | ||
| { | ||
| sb.AppendLine(" // Switch-case instead of dictionary since it does the hashing at compile time rather than run time"); | ||
| sb.AppendLine(" internal static string? LookupType(string type)"); | ||
| sb.AppendLine(" {"); | ||
| sb.AppendLine(" switch (type)"); | ||
| sb.AppendLine(" {"); | ||
|
|
||
| foreach (var kv in data.MimeTypeToExtensions) | ||
| { | ||
| var mimeType = kv.Key; | ||
| var extensions = kv.Value; | ||
|
|
||
| // Generate case statements for all extensions that map to this MIME type | ||
| foreach (var ext in extensions) | ||
| { | ||
| var fieldName = NameUtilities.GetExtensionFieldName(ext); | ||
| sb.AppendLine($" case FileExtensions.{fieldName}:"); | ||
| } | ||
|
|
||
| // Return the MIME type constant (use first extension's field name) | ||
| var firstFieldName = NameUtilities.GetMimeFieldName(extensions[0]); | ||
| sb.AppendLine($" return {firstFieldName};"); | ||
| sb.AppendLine(); | ||
| } | ||
|
|
||
| sb.AppendLine(" default: "); | ||
| sb.AppendLine(" return null;"); | ||
| sb.AppendLine(" }"); | ||
| sb.AppendLine(" }"); | ||
| sb.AppendLine(); | ||
| } | ||
|
|
||
| private static void GenerateLookupMimeTypeMethod(StringBuilder sb, MimeDbData data) | ||
| { | ||
| sb.AppendLine(" // Switch-case instead of dictionary since it does the hashing at compile time rather than run time"); | ||
| sb.AppendLine(" internal static string[]? LookupMimeType(string mimeType)"); | ||
| sb.AppendLine(" {"); | ||
| sb.AppendLine(" switch (mimeType)"); | ||
| sb.AppendLine(" {"); | ||
|
|
||
| foreach (var kv in data.MimeTypeToExtensions) | ||
| { | ||
| var extensions = kv.Value; | ||
| var first = true; | ||
|
|
||
| // Generate case statements for each extension's MIME type constant | ||
| foreach (var ext in extensions) | ||
| { | ||
| var fieldName = NameUtilities.GetMimeFieldName(ext); | ||
| if (first) | ||
| { | ||
| sb.AppendLine($" case {fieldName}:"); | ||
| first = false; | ||
| } | ||
| else | ||
| { | ||
| // Comment out additional cases (they're duplicates pointing to same MIME type) | ||
| sb.AppendLine($" //case {fieldName}:"); | ||
| } | ||
| } | ||
|
|
||
| // Return array of extension constants | ||
| var extFieldNames = new StringBuilder(); | ||
| for (int i = 0; i < extensions.Count; i++) | ||
| { | ||
| if (i > 0) extFieldNames.Append(", "); | ||
| extFieldNames.Append($"FileExtensions.{NameUtilities.GetExtensionFieldName(extensions[i])}"); | ||
| } | ||
| sb.AppendLine($" return new[] {{{extFieldNames}}};"); | ||
| } | ||
|
|
||
| sb.AppendLine(" default: "); | ||
| sb.AppendLine(" return null;"); | ||
| sb.AppendLine(" }"); | ||
| sb.AppendLine(" }"); | ||
| } | ||
| } | ||
| } |
78 changes: 78 additions & 0 deletions
78
src/MimeMapping.SourceGenerator/KnownMimeTypesGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| using System; | ||
| using System.Linq; | ||
| using Microsoft.CodeAnalysis; | ||
|
|
||
| namespace MimeMapping.SourceGenerator | ||
| { | ||
| /// <summary> | ||
| /// Source generator that produces KnownMimeTypes.cs from mime-db JSON data | ||
| /// </summary> | ||
| [Generator] | ||
| public class KnownMimeTypesGenerator : IIncrementalGenerator | ||
| { | ||
| private const string MimeDbFileName = "mime-db.json"; | ||
| private const string MimeDbUrlPropertyName = "build_property.MimeDbUrl"; | ||
| private const string DefaultSourceUrl = "mime-db"; | ||
|
|
||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
| { | ||
| // Find the mime-db.json from AdditionalFiles | ||
| var mimeDbProvider = context.AdditionalTextsProvider | ||
| .Where(file => file.Path.EndsWith(MimeDbFileName, StringComparison.OrdinalIgnoreCase)) | ||
| .Select((file, ct) => file.GetText(ct)?.ToString()) | ||
| .Where(content => !string.IsNullOrEmpty(content)) | ||
| .Collect() | ||
| .Select((contents, ct) => contents.FirstOrDefault()); | ||
|
|
||
| // Get the MimeDbUrl from global options for documentation | ||
| var optionsProvider = context.AnalyzerConfigOptionsProvider | ||
| .Select((provider, ct) => | ||
| { | ||
| provider.GlobalOptions.TryGetValue(MimeDbUrlPropertyName, out var url); | ||
| return url ?? DefaultSourceUrl; | ||
| }); | ||
|
|
||
| // Combine and generate | ||
| var combined = mimeDbProvider.Combine(optionsProvider); | ||
|
|
||
| context.RegisterSourceOutput(combined, (spc, tuple) => | ||
| { | ||
| var (json, sourceUrl) = tuple; | ||
| if (string.IsNullOrEmpty(json)) | ||
| { | ||
| // Report diagnostic if mime-db.json not found | ||
| spc.ReportDiagnostic(Diagnostic.Create( | ||
| new DiagnosticDescriptor( | ||
| "MIME001", | ||
| "mime-db.json not found", | ||
| "The mime-db.json file was not found in AdditionalFiles. Ensure the DownloadMimeDb MSBuild target runs before compilation.", | ||
| "MimeMapping.SourceGenerator", | ||
| DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true), | ||
| Location.None)); | ||
| return; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var data = MimeDbParser.Parse(json!, sourceUrl); | ||
| var source = CodeGenerator.Generate(data); | ||
| spc.AddSource("KnownMimeTypes.g.cs", source); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| spc.ReportDiagnostic(Diagnostic.Create( | ||
| new DiagnosticDescriptor( | ||
| "MIME002", | ||
| "Failed to parse mime-db.json", | ||
| "Failed to parse mime-db.json: {0}", | ||
| "MimeMapping.SourceGenerator", | ||
| DiagnosticSeverity.Error, | ||
| isEnabledByDefault: true), | ||
| Location.None, | ||
| ex.Message)); | ||
| } | ||
| }); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we should convert this to slnx in a follow up for simpler maintenance