diff --git a/Rules/UseConsistentIndentation.cs b/Rules/UseConsistentIndentation.cs index 97c913db5..7c51b98f6 100644 --- a/Rules/UseConsistentIndentation.cs +++ b/Rules/UseConsistentIndentation.cs @@ -360,8 +360,21 @@ private static int GetCommentRunIndentationOffset(Token[] tokens, int tokenIndex precedingIndex--; } + int leastIndentedColumn = tokens[firstCommentIndex].Extent.StartColumnNumber; + for (int nextCommentIndex = firstCommentIndex + 2; + nextCommentIndex < tokens.Length && + tokens[nextCommentIndex - 1].Kind == TokenKind.NewLine && + tokens[nextCommentIndex].Kind == TokenKind.Comment && + tokens[nextCommentIndex].Extent.StartLineNumber == tokens[nextCommentIndex - 2].Extent.EndLineNumber + 1; + nextCommentIndex += 2) + { + leastIndentedColumn = Math.Min( + leastIndentedColumn, + tokens[nextCommentIndex].Extent.StartColumnNumber); + } + return tokens[tokenIndex].Extent.StartColumnNumber - - tokens[firstCommentIndex].Extent.StartColumnNumber; + leastIndentedColumn; } /// diff --git a/Tests/Rules/UseConsistentIndentation.tests.ps1 b/Tests/Rules/UseConsistentIndentation.tests.ps1 index 3a0f325e2..c6418ed49 100644 --- a/Tests/Rules/UseConsistentIndentation.tests.ps1 +++ b/Tests/Rules/UseConsistentIndentation.tests.ps1 @@ -253,6 +253,22 @@ function foo { Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings | Should -Be $expectedScriptDefinition } + + It 'Should preserve indentation when the first comment is not the least-indented with indentation' -TestCases @( + @{ Kind = 'space'; Indentation = ' ' } + @{ Kind = 'tab'; Indentation = "`t" } + ) { + param([string] $Kind, [string] $Indentation) + $scriptDefinition = @( + "$Indentation# inner" + '# outer' + ) -join "`n" + $settings.Rules.PSUseConsistentIndentation.Kind = $Kind + $settings.Rules.PSUseConsistentIndentation.PipelineIndentation = 'NoIndentation' + + Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings | + Should -Be $scriptDefinition + } } Context "When a multi-line command is given" {