-
-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathMatrixDataSourceCodeFixProvider.cs
More file actions
66 lines (55 loc) · 2.55 KB
/
MatrixDataSourceCodeFixProvider.cs
File metadata and controls
66 lines (55 loc) · 2.55 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
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
namespace TUnit.Analyzers.CodeFixers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MatrixDataSourceCodeFixProvider)), Shared]
public class MatrixDataSourceCodeFixProvider : CodeFixProvider
{
private const string Title = "Add [MatrixDataSource]";
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(DiagnosticIds.MatrixDataSourceAttributeRequired);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root is null)
{
return;
}
foreach (var diagnostic in context.Diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan);
var target = node.FirstAncestorOrSelf<SyntaxNode>(n => n is MethodDeclarationSyntax or TypeDeclarationSyntax);
if (target is null)
{
continue;
}
context.RegisterCodeFix(
CodeAction.Create(
title: Title,
createChangedDocument: c => AddMatrixDataSourceAsync(context.Document, target, c),
equivalenceKey: Title),
diagnostic);
}
}
private static async Task<Document> AddMatrixDataSourceAsync(Document document, SyntaxNode target, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var attributeList = SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("MatrixDataSource"))));
SyntaxNode updated = target switch
{
MethodDeclarationSyntax method => method.AddAttributeLists(attributeList),
TypeDeclarationSyntax type => type.AddAttributeLists(attributeList),
_ => throw new InvalidOperationException($"Unexpected node kind: {target.Kind()}"),
};
editor.ReplaceNode(target, updated);
return editor.GetChangedDocument();
}
}