diff --git a/Rules/UseConsistentIndentation.cs b/Rules/UseConsistentIndentation.cs index 0985f39e1..74f3602d6 100644 --- a/Rules/UseConsistentIndentation.cs +++ b/Rules/UseConsistentIndentation.cs @@ -426,6 +426,7 @@ private static int GetCommentRunIndentationOffset( if (precedingIndex < 0 || tokens[precedingIndex].Kind != TokenKind.Comment || HasCodeAfterCommentOnSameLine(tokens, precedingIndex) || + HasCodeBeforeCommentOnSameLine(tokens, precedingIndex) || tokens[precedingIndex].Extent.EndLineNumber != currentLine - 1) { break; @@ -520,6 +521,23 @@ private static bool HasCodeAfterCommentOnSameLine(Token[] tokens, int commentInd nextToken.Extent.StartLineNumber <= commentGroupEndLine; } + private static bool HasCodeBeforeCommentOnSameLine(Token[] tokens, int commentIndex) + { + int commentStartLine = tokens[commentIndex].Extent.StartLineNumber; + int precedingIndex = commentIndex - 1; + while (precedingIndex >= 0 && + tokens[precedingIndex].Kind == TokenKind.Comment && + tokens[precedingIndex].Extent.EndLineNumber >= commentStartLine) + { + precedingIndex--; + } + + return precedingIndex >= 0 && + tokens[precedingIndex].Kind != TokenKind.NewLine && + tokens[precedingIndex].Kind != TokenKind.LineContinuation && + tokens[precedingIndex].Extent.EndLineNumber == commentStartLine; + } + /// /// Scans forward from the current opener to the end of the line. /// Returns true if there is at least one unclosed opener when diff --git a/Tests/Rules/UseConsistentIndentation.tests.ps1 b/Tests/Rules/UseConsistentIndentation.tests.ps1 index e01df4cfd..dd3c04a6a 100644 --- a/Tests/Rules/UseConsistentIndentation.tests.ps1 +++ b/Tests/Rules/UseConsistentIndentation.tests.ps1 @@ -408,6 +408,25 @@ if ($a) { Should -Be $expectedScriptDefinition } + It 'Should not include a trailing inline comment in the following comment run' { + $scriptDefinition = @' +function test { + $value = 1 # trailing + # standalone +} +'@ + $expectedScriptDefinition = @' +function test { + $value = 1 # trailing + # standalone +} +'@ + $settings.Rules.PSUseConsistentIndentation.PipelineIndentation = 'NoIndentation' + + Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings | + Should -Be $expectedScriptDefinition + } + It 'Should not include a multiline block-comment group followed by code in a comment run' { $scriptDefinition = @' if ($a) {