Skip to content

Commit 91e54c2

Browse files
authored
Exclude trailing inline comments from comment runs (#2255)
Add a regression test for standalone comments following trailing inline comments.\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: bergmeister <9250262+bergmeister@users.noreply.github.com>
1 parent 067cbda commit 91e54c2

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

‎Rules/UseConsistentIndentation.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@ private static int GetCommentRunIndentationOffset(
426426
if (precedingIndex < 0 ||
427427
tokens[precedingIndex].Kind != TokenKind.Comment ||
428428
HasCodeAfterCommentOnSameLine(tokens, precedingIndex) ||
429+
HasCodeBeforeCommentOnSameLine(tokens, precedingIndex) ||
429430
tokens[precedingIndex].Extent.EndLineNumber != currentLine - 1)
430431
{
431432
break;
@@ -520,6 +521,23 @@ private static bool HasCodeAfterCommentOnSameLine(Token[] tokens, int commentInd
520521
nextToken.Extent.StartLineNumber <= commentGroupEndLine;
521522
}
522523

524+
private static bool HasCodeBeforeCommentOnSameLine(Token[] tokens, int commentIndex)
525+
{
526+
int commentStartLine = tokens[commentIndex].Extent.StartLineNumber;
527+
int precedingIndex = commentIndex - 1;
528+
while (precedingIndex >= 0 &&
529+
tokens[precedingIndex].Kind == TokenKind.Comment &&
530+
tokens[precedingIndex].Extent.EndLineNumber >= commentStartLine)
531+
{
532+
precedingIndex--;
533+
}
534+
535+
return precedingIndex >= 0 &&
536+
tokens[precedingIndex].Kind != TokenKind.NewLine &&
537+
tokens[precedingIndex].Kind != TokenKind.LineContinuation &&
538+
tokens[precedingIndex].Extent.EndLineNumber == commentStartLine;
539+
}
540+
523541
/// <summary>
524542
/// Scans forward from the current opener to the end of the line.
525543
/// Returns true if there is at least one unclosed opener when

‎Tests/Rules/UseConsistentIndentation.tests.ps1‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,25 @@ if ($a) {
408408
Should -Be $expectedScriptDefinition
409409
}
410410

411+
It 'Should not include a trailing inline comment in the following comment run' {
412+
$scriptDefinition = @'
413+
function test {
414+
$value = 1 # trailing
415+
# standalone
416+
}
417+
'@
418+
$expectedScriptDefinition = @'
419+
function test {
420+
$value = 1 # trailing
421+
# standalone
422+
}
423+
'@
424+
$settings.Rules.PSUseConsistentIndentation.PipelineIndentation = 'NoIndentation'
425+
426+
Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings |
427+
Should -Be $expectedScriptDefinition
428+
}
429+
411430
It 'Should not include a multiline block-comment group followed by code in a comment run' {
412431
$scriptDefinition = @'
413432
if ($a) {

0 commit comments

Comments
 (0)