|
| 1 | +using Microsoft.CodeAnalysis; |
| 2 | +using Microsoft.CodeAnalysis.CSharp; |
| 3 | +using Microsoft.CodeAnalysis.Text; |
| 4 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 5 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 6 | +using System.Collections.Immutable; |
| 7 | +using System.Collections.ObjectModel; |
| 8 | +using System.ComponentModel; |
| 9 | +using System.Drawing; |
| 10 | +using Microsoft.CodeAnalysis.CodeActions; |
| 11 | +using Terminal.Gui.ViewBase; |
| 12 | +using Terminal.Gui.Views; |
| 13 | +using Document = Microsoft.CodeAnalysis.Document; |
| 14 | +using Formatter = Microsoft.CodeAnalysis.Formatting.Formatter; |
| 15 | +using System.Reflection; |
| 16 | +using JetBrains.Annotations; |
| 17 | + |
| 18 | +public sealed class ProjectBuilder |
| 19 | +{ |
| 20 | + private string _sourceCode; |
| 21 | + private string _expectedFixedCode; |
| 22 | + private DiagnosticAnalyzer _analyzer; |
| 23 | + private CodeFixProvider _codeFix; |
| 24 | + |
| 25 | + public ProjectBuilder WithSourceCode (string source) |
| 26 | + { |
| 27 | + _sourceCode = source; |
| 28 | + return this; |
| 29 | + } |
| 30 | + |
| 31 | + public ProjectBuilder ShouldFixCodeWith (string expected) |
| 32 | + { |
| 33 | + _expectedFixedCode = expected; |
| 34 | + return this; |
| 35 | + } |
| 36 | + |
| 37 | + public ProjectBuilder WithAnalyzer (DiagnosticAnalyzer analyzer) |
| 38 | + { |
| 39 | + _analyzer = analyzer; |
| 40 | + return this; |
| 41 | + } |
| 42 | + |
| 43 | + public ProjectBuilder WithCodeFix (CodeFixProvider codeFix) |
| 44 | + { |
| 45 | + _codeFix = codeFix; |
| 46 | + return this; |
| 47 | + } |
| 48 | + |
| 49 | + public async Task ValidateAsync () |
| 50 | + { |
| 51 | + if (_sourceCode == null) |
| 52 | + { |
| 53 | + throw new InvalidOperationException ("Source code not set."); |
| 54 | + } |
| 55 | + |
| 56 | + if (_analyzer == null) |
| 57 | + { |
| 58 | + throw new InvalidOperationException ("Analyzer not set."); |
| 59 | + } |
| 60 | + |
| 61 | + // Parse original document |
| 62 | + var document = CreateDocument (_sourceCode); |
| 63 | + var compilation = await document.Project.GetCompilationAsync (); |
| 64 | + |
| 65 | + var diagnostics = compilation.GetDiagnostics (); |
| 66 | + var errors = diagnostics.Where (d => d.Severity == DiagnosticSeverity.Error); |
| 67 | + |
| 68 | + if (errors.Any ()) |
| 69 | + { |
| 70 | + var errorMessages = string.Join (Environment.NewLine, errors.Select (e => e.ToString ())); |
| 71 | + throw new Exception ("Compilation failed with errors:" + Environment.NewLine + errorMessages); |
| 72 | + } |
| 73 | + |
| 74 | + // Run analyzer |
| 75 | + var analyzerDiagnostics = await GetAnalyzerDiagnosticsAsync (compilation, _analyzer); |
| 76 | + |
| 77 | + Assert.NotEmpty (analyzerDiagnostics); |
| 78 | + |
| 79 | + if (_expectedFixedCode != null) |
| 80 | + { |
| 81 | + if (_codeFix == null) |
| 82 | + { |
| 83 | + throw new InvalidOperationException ("Expected code fix but none was set."); |
| 84 | + } |
| 85 | + |
| 86 | + var fixedDocument = await ApplyCodeFixAsync (document, analyzerDiagnostics.First (), _codeFix); |
| 87 | + |
| 88 | + var formattedDocument = await Formatter.FormatAsync (fixedDocument); |
| 89 | + var fixedSource = (await formattedDocument.GetTextAsync ()).ToString (); |
| 90 | + |
| 91 | + Assert.Equal (_expectedFixedCode, fixedSource); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private static Document CreateDocument (string source) |
| 96 | + { |
| 97 | + var dd = typeof (Enumerable).GetTypeInfo ().Assembly.Location; |
| 98 | + var coreDir = Directory.GetParent (dd) ?? throw new Exception ($"Could not find parent directory of dotnet sdk. Sdk directory was {dd}"); |
| 99 | + |
| 100 | + var workspace = new AdhocWorkspace (); |
| 101 | + var projectId = ProjectId.CreateNewId (); |
| 102 | + var documentId = DocumentId.CreateNewId (projectId); |
| 103 | + |
| 104 | + var references = new List<MetadataReference> () |
| 105 | + { |
| 106 | + MetadataReference.CreateFromFile(typeof(Button).Assembly.Location), |
| 107 | + MetadataReference.CreateFromFile(typeof(View).Assembly.Location), |
| 108 | + MetadataReference.CreateFromFile(typeof(System.IO.FileSystemInfo).Assembly.Location), |
| 109 | + MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location), |
| 110 | + MetadataReference.CreateFromFile(typeof(object).Assembly.Location), |
| 111 | + MetadataReference.CreateFromFile(typeof(MarshalByValueComponent).Assembly.Location), |
| 112 | + MetadataReference.CreateFromFile(typeof(ObservableCollection<string>).Assembly.Location), |
| 113 | + |
| 114 | + // New assemblies required by Terminal.Gui version 2 |
| 115 | + MetadataReference.CreateFromFile(typeof(Size).Assembly.Location), |
| 116 | + MetadataReference.CreateFromFile(typeof(CanBeNullAttribute).Assembly.Location), |
| 117 | + |
| 118 | + |
| 119 | + MetadataReference.CreateFromFile(Path.Combine(coreDir.FullName, "mscorlib.dll")), |
| 120 | + MetadataReference.CreateFromFile(Path.Combine(coreDir.FullName, "System.Runtime.dll")), |
| 121 | + MetadataReference.CreateFromFile(Path.Combine(coreDir.FullName, "System.Collections.dll")), |
| 122 | + MetadataReference.CreateFromFile(Path.Combine(coreDir.FullName, "System.Data.Common.dll")), |
| 123 | + // Add more as necessary |
| 124 | + }; |
| 125 | + |
| 126 | + |
| 127 | + var projectInfo = ProjectInfo.Create ( |
| 128 | + projectId, |
| 129 | + VersionStamp.Create (), |
| 130 | + "TestProject", |
| 131 | + "TestAssembly", |
| 132 | + LanguageNames.CSharp, |
| 133 | + compilationOptions: new CSharpCompilationOptions (OutputKind.DynamicallyLinkedLibrary), |
| 134 | + metadataReferences: references); |
| 135 | + |
| 136 | + var solution = workspace.CurrentSolution |
| 137 | + .AddProject (projectInfo) |
| 138 | + .AddDocument (documentId, "Test.cs", SourceText.From (source)); |
| 139 | + |
| 140 | + return solution.GetDocument (documentId)!; |
| 141 | + } |
| 142 | + |
| 143 | + private static async Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsAsync (Compilation compilation, DiagnosticAnalyzer analyzer) |
| 144 | + { |
| 145 | + var compilationWithAnalyzers = compilation.WithAnalyzers (ImmutableArray.Create (analyzer)); |
| 146 | + return await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync (); |
| 147 | + } |
| 148 | + |
| 149 | + private static async Task<Document> ApplyCodeFixAsync (Document document, Diagnostic diagnostic, CodeFixProvider codeFix) |
| 150 | + { |
| 151 | + CodeAction _codeAction = null; |
| 152 | + var context = new CodeFixContext ((TextDocument)document, diagnostic, (action, _) => _codeAction = action, CancellationToken.None); |
| 153 | + |
| 154 | + await codeFix.RegisterCodeFixesAsync (context); |
| 155 | + |
| 156 | + if (_codeAction == null) |
| 157 | + { |
| 158 | + throw new InvalidOperationException ("Code fix did not register a fix."); |
| 159 | + } |
| 160 | + |
| 161 | + var operations = await _codeAction.GetOperationsAsync (CancellationToken.None); |
| 162 | + var solution = operations.OfType<ApplyChangesOperation> ().First ().ChangedSolution; |
| 163 | + return solution.GetDocument (document.Id); |
| 164 | + } |
| 165 | +} |
0 commit comments