Skip to content

Commit c6479d5

Browse files
authored
Handling an edge case where usings are reordered inside of a namespac… (#1543)
…e inside of an #if
1 parent 9cf0eaf commit c6479d5

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

Src/CSharpier.Tests/CommandLineFormatterTests.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,34 @@ public void File_With_Reorder_Modifiers_In_If_Directive_Should_Pass_Validation(s
678678
result.OutputLines.First().Should().StartWith("Formatted 1 files in");
679679
}
680680

681+
[Test]
682+
public void File_With_Reordered_Usings_In_If_Directive_Should_Pass_Validation()
683+
{
684+
var context = new TestContext();
685+
686+
context.WhenAFileExists(
687+
"file1.cs",
688+
"""
689+
#if NOT_UNTIL_LATER
690+
namespace Namespace {
691+
692+
using System.Xml;
693+
using System.Configuration;
694+
695+
public class ClassName {
696+
697+
}
698+
}
699+
#endif
700+
"""
701+
);
702+
703+
var result = Format(context);
704+
705+
result.ErrorOutputLines.Should().BeEmpty();
706+
result.OutputLines.First().Should().StartWith("Formatted 1 files in");
707+
}
708+
681709
[Test]
682710
public void File_With_Added_Trailing_Comma_Before_Comment_Should_Pass_Validation()
683711
{

Src/CSharpier/SyntaxPrinter/UsingDirectives.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,16 @@ var groupOfUsingData in GroupUsings(
124124
}
125125
}
126126

127-
if (reorderedDirectives && usings.Any(o => o.ToFullString().Contains("#endif")))
127+
if (
128+
reorderedDirectives
129+
&& (
130+
usings.Any(o => o.ToFullString().Contains("#endif"))
131+
|| (
132+
usings[0].Parent is NamespaceDeclarationSyntax namespaceDeclarationSyntax
133+
&& namespaceDeclarationSyntax.GetLeadingTrivia().ToFullString().Contains("#if")
134+
)
135+
)
136+
)
128137
{
129138
context.State.ReorderedUsingsWithDisabledText = true;
130139
}

0 commit comments

Comments
 (0)