Skip to content

Commit 5c23cbc

Browse files
committed
Implement a custom fix-all provider for SA1027
1 parent de3959a commit 5c23cbc

1 file changed

Lines changed: 34 additions & 1 deletion

File tree

StyleCop.Analyzers/StyleCop.Analyzers/SpacingRules/SA1027CodeFixProvider.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
namespace StyleCop.Analyzers.SpacingRules
55
{
6+
using System.Collections.Generic;
67
using System.Collections.Immutable;
78
using System.Composition;
89
using System.Linq;
@@ -31,7 +32,7 @@ public class SA1027CodeFixProvider : CodeFixProvider
3132
/// <inheritdoc/>
3233
public override FixAllProvider GetFixAllProvider()
3334
{
34-
return CustomFixAllProviders.BatchFixer;
35+
return FixAll.Instance;
3536
}
3637

3738
/// <inheritdoc/>
@@ -95,5 +96,37 @@ private static TextChange FixDiagnostic(IndentationOptions indentationOptions, S
9596

9697
return new TextChange(span, replacement.ToString());
9798
}
99+
100+
private class FixAll : DocumentBasedFixAllProvider
101+
{
102+
public static FixAllProvider Instance { get; }
103+
= new FixAll();
104+
105+
protected override string CodeActionTitle
106+
=> SpacingResources.SA1027CodeFix;
107+
108+
protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document)
109+
{
110+
var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
111+
if (diagnostics.IsEmpty)
112+
{
113+
return null;
114+
}
115+
116+
var indentationOptions = IndentationOptions.FromDocument(document);
117+
SourceText sourceText = await document.GetTextAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
118+
119+
List<TextChange> changes = new List<TextChange>();
120+
foreach (var diagnostic in diagnostics)
121+
{
122+
changes.Add(FixDiagnostic(indentationOptions, sourceText, diagnostic));
123+
}
124+
125+
changes.Sort((left, right) => left.Span.Start.CompareTo(right.Span.Start));
126+
127+
SyntaxTree tree = await document.GetSyntaxTreeAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
128+
return await tree.WithChangedText(sourceText.WithChanges(changes)).GetRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
129+
}
130+
}
98131
}
99132
}

0 commit comments

Comments
 (0)