-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
NamespaceDeclarationCodeFixProvider.cs
67 lines (58 loc) · 2.63 KB
/
NamespaceDeclarationCodeFixProvider.cs
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
67
// Copyright (c) .NET Foundation and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslynator.CodeFixes;
using Roslynator.CSharp.Refactorings;
namespace Roslynator.CSharp.CodeFixes;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(NamespaceDeclarationCodeFixProvider))]
[Shared]
public sealed class NamespaceDeclarationCodeFixProvider : BaseCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
return ImmutableArray.Create(
DiagnosticIdentifiers.RemoveEmptyNamespaceDeclaration,
DiagnosticIdentifiers.DeclareUsingDirectiveOnTopLevel);
}
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);
if (!TryFindFirstAncestorOrSelf(root, context.Span, out NamespaceDeclarationSyntax namespaceDeclaration))
return;
foreach (Diagnostic diagnostic in context.Diagnostics)
{
switch (diagnostic.Id)
{
case DiagnosticIdentifiers.RemoveEmptyNamespaceDeclaration:
{
CodeAction codeAction = CodeAction.Create(
"Remove empty namespace declaration",
ct => context.Document.RemoveNodeAsync(namespaceDeclaration, ct),
GetEquivalenceKey(diagnostic));
context.RegisterCodeFix(codeAction, diagnostic);
break;
}
case DiagnosticIdentifiers.DeclareUsingDirectiveOnTopLevel:
{
string title = (namespaceDeclaration.Usings.Count == 1)
? "Move using to top level"
: "Move usings to top level";
CodeAction codeAction = CodeAction.Create(
title,
ct => DeclareUsingDirectiveOnTopLevelRefactoring.RefactorAsync(context.Document, namespaceDeclaration, ct),
GetEquivalenceKey(diagnostic));
context.RegisterCodeFix(codeAction, diagnostic);
break;
}
}
}
}
}