Skip to content

Commit b1c6db9

Browse files
committed
Implement a custom Fix All provider for SA1513
1 parent ab5993f commit b1c6db9

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/LayoutRules/SA1513CodeFixProvider.cs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ namespace StyleCop.Analyzers.LayoutRules
55
{
66
using System.Collections.Immutable;
77
using System.Composition;
8+
using System.Linq;
89
using System.Threading;
910
using System.Threading.Tasks;
1011
using Microsoft.CodeAnalysis;
@@ -30,7 +31,7 @@ internal class SA1513CodeFixProvider : CodeFixProvider
3031
/// <inheritdoc/>
3132
public override FixAllProvider GetFixAllProvider()
3233
{
33-
return CustomFixAllProviders.BatchFixer;
34+
return FixAll.Instance;
3435
}
3536

3637
/// <inheritdoc/>
@@ -51,15 +52,31 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
5152

5253
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
5354
{
54-
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
55-
var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.End);
55+
var newRoot = await GetTransformedDocumentAsync(document, ImmutableArray.Create(diagnostic), cancellationToken).ConfigureAwait(false);
56+
return document.WithSyntaxRoot(newRoot);
57+
}
58+
59+
private static async Task<SyntaxNode> GetTransformedDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
60+
{
61+
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
62+
return root.ReplaceTokens(
63+
diagnostics.Select(diagnostic => root.FindToken(diagnostic.Location.SourceSpan.End)),
64+
(originalToken, rewrittenToken) =>
65+
{
66+
var newTrivia = rewrittenToken.LeadingTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed);
67+
return rewrittenToken.WithLeadingTrivia(newTrivia);
68+
});
69+
}
70+
71+
private class FixAll : DocumentBasedFixAllProvider
72+
{
73+
public static FixAllProvider Instance { get; } =
74+
new FixAll();
5675

57-
var newTrivia = token.LeadingTrivia.Insert(0, SyntaxFactory.CarriageReturnLineFeed);
58-
var newToken = token.WithLeadingTrivia(newTrivia);
59-
var newSyntaxRoot = syntaxRoot.ReplaceToken(token, newToken);
60-
var newDocument = document.WithSyntaxRoot(newSyntaxRoot);
76+
protected override string CodeActionTitle => LayoutResources.SA1513CodeFix;
6177

62-
return newDocument;
78+
protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
79+
=> await GetTransformedDocumentAsync(document, diagnostics, fixAllContext.CancellationToken).ConfigureAwait(false);
6380
}
6481
}
6582
}

0 commit comments

Comments
 (0)