|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Apollo.Infrastructure.Workers; |
| 3 | +using Microsoft.AspNetCore.Razor.Language; |
| 4 | + |
| 5 | +namespace Apollo.Analysis; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Extracts C# code from Razor files using the Razor compiler. |
| 9 | +/// Provides source mappings to translate positions between generated C# and original Razor. |
| 10 | +/// </summary> |
| 11 | +public class RazorCodeExtractor |
| 12 | +{ |
| 13 | + private readonly ILoggerProxy _logger; |
| 14 | + |
| 15 | + public RazorCodeExtractor(ILoggerProxy logger) |
| 16 | + { |
| 17 | + _logger = logger; |
| 18 | + } |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Parse a Razor file and return the extraction result containing generated C# and source mappings. |
| 22 | + /// </summary> |
| 23 | + public RazorExtractionResult Extract(string razorContent, string filePath) |
| 24 | + { |
| 25 | + try |
| 26 | + { |
| 27 | + // Create a minimal file system for the Razor engine |
| 28 | + var fileSystem = new VirtualRazorProjectFileSystem(); |
| 29 | + |
| 30 | + // Determine file kind based on extension |
| 31 | + var fileKind = filePath.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase) |
| 32 | + ? FileKinds.Legacy |
| 33 | + : FileKinds.Component; |
| 34 | + |
| 35 | + // Create the Razor project engine with component configuration |
| 36 | + var projectEngine = RazorProjectEngine.Create( |
| 37 | + RazorConfiguration.Default, |
| 38 | + fileSystem, |
| 39 | + builder => |
| 40 | + { |
| 41 | + // Configure for Blazor component compilation |
| 42 | + builder.SetRootNamespace("Apollo.Generated"); |
| 43 | + }); |
| 44 | + |
| 45 | + // Create a source document from the Razor content |
| 46 | + var sourceDocument = RazorSourceDocument.Create(razorContent, filePath); |
| 47 | + |
| 48 | + // Create and process the code document |
| 49 | + var codeDocument = projectEngine.Process( |
| 50 | + sourceDocument, |
| 51 | + fileKind, |
| 52 | + ImmutableArray<RazorSourceDocument>.Empty, |
| 53 | + tagHelpers: null); |
| 54 | + |
| 55 | + // Get the generated C# document |
| 56 | + var csharpDocument = codeDocument.GetCSharpDocument(); |
| 57 | + if (csharpDocument == null) |
| 58 | + { |
| 59 | + _logger.LogTrace($"Failed to generate C# from Razor file: {filePath}"); |
| 60 | + return RazorExtractionResult.Empty; |
| 61 | + } |
| 62 | + |
| 63 | + // Log any diagnostics from Razor compilation |
| 64 | + foreach (var diagnostic in csharpDocument.Diagnostics) |
| 65 | + { |
| 66 | + _logger.LogTrace($"Razor diagnostic in {filePath}: {diagnostic.GetMessage()}"); |
| 67 | + } |
| 68 | + |
| 69 | + // Get syntax tree |
| 70 | + var syntaxTree = codeDocument.GetSyntaxTree(); |
| 71 | + |
| 72 | + return new RazorExtractionResult |
| 73 | + { |
| 74 | + GeneratedCode = csharpDocument.GeneratedCode, |
| 75 | + SourceMappings = csharpDocument.SourceMappings.ToList(), |
| 76 | + SyntaxTree = syntaxTree |
| 77 | + }; |
| 78 | + } |
| 79 | + catch (Exception ex) |
| 80 | + { |
| 81 | + _logger.LogTrace($"Error extracting C# from Razor file {filePath}: {ex.Message}"); |
| 82 | + return RazorExtractionResult.Empty; |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +/// <summary> |
| 88 | +/// Result of Razor extraction containing generated C# code and source mappings. |
| 89 | +/// </summary> |
| 90 | +public class RazorExtractionResult |
| 91 | +{ |
| 92 | + /// <summary> |
| 93 | + /// The generated C# code that can be analyzed by Roslyn. |
| 94 | + /// </summary> |
| 95 | + public string GeneratedCode { get; init; } = ""; |
| 96 | + |
| 97 | + /// <summary> |
| 98 | + /// Source mappings that map spans in generated C# back to original Razor positions. |
| 99 | + /// </summary> |
| 100 | + public List<SourceMapping> SourceMappings { get; init; } = []; |
| 101 | + |
| 102 | + /// <summary> |
| 103 | + /// The Razor syntax tree for component detection. |
| 104 | + /// </summary> |
| 105 | + public RazorSyntaxTree? SyntaxTree { get; init; } |
| 106 | + |
| 107 | + /// <summary> |
| 108 | + /// An empty extraction result. |
| 109 | + /// </summary> |
| 110 | + public static RazorExtractionResult Empty => new(); |
| 111 | + |
| 112 | + /// <summary> |
| 113 | + /// Whether this result has valid generated code. |
| 114 | + /// </summary> |
| 115 | + public bool IsEmpty => string.IsNullOrEmpty(GeneratedCode); |
| 116 | +} |
| 117 | + |
| 118 | +/// <summary> |
| 119 | +/// A virtual file system implementation for the Razor project engine. |
| 120 | +/// Since we're processing in-memory content, we don't need actual file system access. |
| 121 | +/// </summary> |
| 122 | +internal class VirtualRazorProjectFileSystem : RazorProjectFileSystem |
| 123 | +{ |
| 124 | + public override IEnumerable<RazorProjectItem> EnumerateItems(string basePath) |
| 125 | + { |
| 126 | + return Enumerable.Empty<RazorProjectItem>(); |
| 127 | + } |
| 128 | + |
| 129 | + public override RazorProjectItem GetItem(string path) |
| 130 | + { |
| 131 | + return new NotFoundProjectItem(string.Empty, path, FileKinds.Component); |
| 132 | + } |
| 133 | + |
| 134 | + public override RazorProjectItem GetItem(string path, string? fileKind) |
| 135 | + { |
| 136 | + return new NotFoundProjectItem(string.Empty, path, fileKind ?? FileKinds.Component); |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +/// <summary> |
| 141 | +/// Represents a project item that was not found. |
| 142 | +/// </summary> |
| 143 | +internal class NotFoundProjectItem : RazorProjectItem |
| 144 | +{ |
| 145 | + public NotFoundProjectItem(string basePath, string path, string fileKind) |
| 146 | + { |
| 147 | + BasePath = basePath; |
| 148 | + FilePath = path; |
| 149 | + FileKind = fileKind; |
| 150 | + } |
| 151 | + |
| 152 | + public override string BasePath { get; } |
| 153 | + public override string FilePath { get; } |
| 154 | + public override string FileKind { get; } |
| 155 | + public override bool Exists => false; |
| 156 | + public override string PhysicalPath => FilePath; |
| 157 | + |
| 158 | + public override Stream Read() |
| 159 | + { |
| 160 | + throw new InvalidOperationException("Item does not exist"); |
| 161 | + } |
| 162 | +} |
0 commit comments