Skip to content

Commit ff402a3

Browse files
committed
Port pull request #1963 to stabilization
Fix SA1133 handling of whitespace in code fix (cherry picked from commit ff4ac5f)
1 parent 4ec134a commit ff402a3

2 files changed

Lines changed: 48 additions & 1 deletion

File tree

StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/ReadabilityRules/SA1133CodeFixProvider.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ private static List<AttributeListSyntax> GetNewAttributeList(AttributeListSyntax
7777

7878
for (var i = 0; i < attributeList.Attributes.Count; i++)
7979
{
80-
var newAttributes = SyntaxFactory.SingletonSeparatedList(attributeList.Attributes[i]);
80+
var newAttributes = SyntaxFactory.SingletonSeparatedList(
81+
attributeList.Attributes[i].WithLeadingTrivia(
82+
attributeList.Attributes[i].GetLeadingTrivia().WithoutLeadingWhitespace()));
8183
var newAttributeList = SyntaxFactory.AttributeList(attributeList.Target, newAttributes);
8284

8385
newAttributeList = (i == 0)

StyleCop.Analyzers/StyleCop.Analyzers.Test/ReadabilityRules/SA1133UnitTests.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,51 @@ public enum ImplicitUseKindFlags { Assign }
421421
await this.VerifyCSharpFixAllFixAsync(testCode, fixedTestCode, maxNumberOfIterations: 1).ConfigureAwait(false);
422422
}
423423

424+
/// <summary>
425+
/// Regression test for issue 1883 (whitespace is preserved incorrectly): https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1883
426+
/// </summary>
427+
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
428+
[Fact]
429+
public async Task TestWhitespaceIsHandledCorrectlyAsync()
430+
{
431+
var testCode = @"
432+
namespace SA1133CodeFix
433+
{
434+
using System.ComponentModel;
435+
using System.Diagnostics.CodeAnalysis;
436+
437+
[DefaultValue(true),
438+
SuppressMessage(null, null)]
439+
internal class Foo
440+
{
441+
}
442+
}
443+
";
444+
445+
var fixedTestCode = @"
446+
namespace SA1133CodeFix
447+
{
448+
using System.ComponentModel;
449+
using System.Diagnostics.CodeAnalysis;
450+
451+
[DefaultValue(true)]
452+
[SuppressMessage(null, null)]
453+
internal class Foo
454+
{
455+
}
456+
}
457+
";
458+
459+
DiagnosticResult[] expected =
460+
{
461+
this.CSharpDiagnostic().WithLocation(8, 5)
462+
};
463+
464+
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
465+
await this.VerifyCSharpDiagnosticAsync(fixedTestCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
466+
await this.VerifyCSharpFixAsync(testCode, fixedTestCode).ConfigureAwait(false);
467+
}
468+
424469
/// <inheritdoc/>
425470
protected override CodeFixProvider GetCSharpCodeFixProvider()
426471
{

0 commit comments

Comments
 (0)