-
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathDoNotRemoveOriginalExceptionFromThrowStatementFixer.cs
More file actions
46 lines (37 loc) · 1.81 KB
/
Copy pathDoNotRemoveOriginalExceptionFromThrowStatementFixer.cs
File metadata and controls
46 lines (37 loc) · 1.81 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
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
namespace Meziantou.Analyzer.Rules;
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class DoNotRemoveOriginalExceptionFromThrowStatementFixer : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(RuleIdentifiers.DoNotRemoveOriginalExceptionFromThrowStatement);
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true);
if (nodeToFix is null)
return;
var title = "Throw original exception";
var codeAction = CodeAction.Create(
title,
ct => Fix(context.Document, nodeToFix, ct),
equivalenceKey: title);
context.RegisterCodeFix(codeAction, context.Diagnostics);
}
private static async Task<Document> Fix(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken)
{
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var syntax = (ThrowStatementSyntax)nodeToFix;
if (syntax is null)
return document;
editor.ReplaceNode(syntax, syntax.WithExpression(null).WithAdditionalAnnotations(Formatter.Annotation));
return editor.GetChangedDocument();
}
}