Skip to content

Commit

Permalink
Implement a custom Fix All provider for SA1510
Browse files Browse the repository at this point in the history
  • Loading branch information
sharwell committed Mar 17, 2021
1 parent d84d836 commit 92a0b27
Showing 1 changed file with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace StyleCop.Analyzers.LayoutRules
{
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
Expand All @@ -26,7 +27,7 @@ internal class SA1510CodeFixProvider : CodeFixProvider
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
return CustomFixAllProviders.BatchFixer;
return FixAll.Instance;
}

/// <inheritdoc/>
Expand All @@ -46,13 +47,31 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
}

private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var newRoot = await GetTransformedDocumentAsync(document, ImmutableArray.Create(diagnostic), cancellationToken).ConfigureAwait(false);
return document.WithSyntaxRoot(newRoot);
}

private static async Task<SyntaxNode> GetTransformedDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return syntaxRoot.ReplaceTokens(
diagnostics.Select(diagnostic => syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start)),
(originalToken, rewrittenToken) =>
{
return rewrittenToken.WithoutLeadingBlankLines();
});
}

private class FixAll : DocumentBasedFixAllProvider
{
public static FixAllProvider Instance { get; } =
new FixAll();

var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
protected override string CodeActionTitle => LayoutResources.SA1510CodeFix;

var newSyntaxRoot = syntaxRoot.ReplaceToken(token, token.WithoutLeadingBlankLines());
return document.WithSyntaxRoot(newSyntaxRoot);
protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
=> await GetTransformedDocumentAsync(document, diagnostics, fixAllContext.CancellationToken).ConfigureAwait(false);
}
}
}

0 comments on commit 92a0b27

Please sign in to comment.