|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Linq; |
| 5 | +using System.Threading; |
| 6 | +using System.Collections.Immutable; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.AspNetCore.Analyzers.DelegateEndpoints; |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.CodeAnalysis.CSharp; |
| 11 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 12 | +using Microsoft.CodeAnalysis.CodeFixes; |
| 13 | +using Microsoft.CodeAnalysis.CodeActions; |
| 14 | +using Microsoft.CodeAnalysis.Editing; |
| 15 | + |
| 16 | +namespace Microsoft.AspNetCore.Analyzers.DelegateEndpoints.Fixers; |
| 17 | + |
| 18 | +public class DetectMismatchedParameterOptionalityFixer : CodeFixProvider |
| 19 | +{ |
| 20 | + public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(DiagnosticDescriptors.DetectMismatchedParameterOptionality.Id); |
| 21 | + |
| 22 | + public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; |
| 23 | + |
| 24 | + public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) |
| 25 | + { |
| 26 | + foreach (var diagnostic in context.Diagnostics) |
| 27 | + { |
| 28 | + context.RegisterCodeFix( |
| 29 | + CodeAction.Create("Fix mismatched route parameter and argument optionality", |
| 30 | + cancellationToken => FixMismatchedParameterOptionality(context, cancellationToken), |
| 31 | + equivalenceKey: DiagnosticDescriptors.DetectMismatchedParameterOptionality.Id), |
| 32 | + diagnostic); |
| 33 | + } |
| 34 | + |
| 35 | + return Task.CompletedTask; |
| 36 | + } |
| 37 | + |
| 38 | + private static async Task<Document> FixMismatchedParameterOptionality(CodeFixContext context, CancellationToken cancellationToken) |
| 39 | + { |
| 40 | + DocumentEditor editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken); |
| 41 | + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); |
| 42 | + |
| 43 | + if (root == null) |
| 44 | + { |
| 45 | + return context.Document; |
| 46 | + } |
| 47 | + |
| 48 | + var diagnostic = context.Diagnostics.SingleOrDefault(); |
| 49 | + |
| 50 | + if (diagnostic == null) |
| 51 | + { |
| 52 | + return context.Document; |
| 53 | + } |
| 54 | + |
| 55 | + var param = root.FindNode(diagnostic.Location.SourceSpan); |
| 56 | + if (param != null && param is ParameterSyntax parameterSyntax) |
| 57 | + { |
| 58 | + if (parameterSyntax.Type != null) |
| 59 | + { |
| 60 | + var newParam = parameterSyntax.WithType(SyntaxFactory.NullableType(parameterSyntax.Type)); |
| 61 | + editor.ReplaceNode(parameterSyntax, newParam); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return editor.GetChangedDocument(); |
| 66 | + } |
| 67 | +} |
0 commit comments