Skip to content

Commit

Permalink
Merge pull request DotNetAnalyzers#3767 from bjornhellander/feature/s…
Browse files Browse the repository at this point in the history
…a1629-custom-fixer-2957

Update to use a custom fixer for SA1629
  • Loading branch information
sharwell authored Jan 17, 2024
2 parents 54a37e3 + 58e9d96 commit f5f4ca9
Showing 1 changed file with 40 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace StyleCop.Analyzers.DocumentationRules
{
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
Expand All @@ -29,7 +30,7 @@ internal class SA1629CodeFixProvider : CodeFixProvider
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
return CustomFixAllProviders.BatchFixer;
return FixAll.Instance;
}

/// <inheritdoc/>
Expand All @@ -54,10 +55,46 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
bool replaceChar = diagnostic.Properties.ContainsKey(SA1629DocumentationTextMustEndWithAPeriod.ReplaceCharKey);
var newText = text.WithChanges(new TextChange(new TextSpan(diagnostic.Location.SourceSpan.Start, replaceChar ? 1 : 0), "."));
var textChange = GetTextChange(diagnostic);
var newText = text.WithChanges(textChange);

return document.WithText(newText);
}

private static TextChange GetTextChange(Diagnostic diagnostic)
{
var replaceChar = diagnostic.Properties.ContainsKey(SA1629DocumentationTextMustEndWithAPeriod.ReplaceCharKey);
var textChange = new TextChange(new TextSpan(diagnostic.Location.SourceSpan.Start, replaceChar ? 1 : 0), ".");
return textChange;
}

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

protected override string CodeActionTitle =>
DocumentationResources.SA1629CodeFix;

protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
{
if (diagnostics.IsEmpty)
{
return null;
}

var changes = new List<TextChange>();
foreach (var diagnostic in diagnostics)
{
changes.Add(GetTextChange(diagnostic));
}

changes.Sort((left, right) => left.Span.Start.CompareTo(right.Span.Start));

var text = await document.GetTextAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
var tree = await document.GetSyntaxTreeAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
return await tree.WithChangedText(text.WithChanges(changes)).GetRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
}
}
}
}

0 comments on commit f5f4ca9

Please sign in to comment.