diff --git a/Rules/UseConsistentIndentation.cs b/Rules/UseConsistentIndentation.cs index 43a4f071f..8f17e2462 100644 --- a/Rules/UseConsistentIndentation.cs +++ b/Rules/UseConsistentIndentation.cs @@ -155,8 +155,8 @@ public override IEnumerable AnalyzeScript(Ast ast, string file case TokenKind.Pipe: if (pipelineIndentationStyle == PipelineIndentationStyle.None) { break; } - bool pipelineIsFollowedByNewlineOrLineContinuation = tokenIndex < tokens.Length - 1 && tokenIndex > 0 && - (tokens[tokenIndex + 1].Kind == TokenKind.NewLine || tokens[tokenIndex + 1].Kind == TokenKind.LineContinuation); + bool pipelineIsFollowedByNewlineOrLineContinuation = + PipelineIsFollowedByNewlineOrLineContinuation(tokens, tokenIndex); if (!pipelineIsFollowedByNewlineOrLineContinuation) { break; @@ -254,6 +254,36 @@ public override IEnumerable AnalyzeScript(Ast ast, string file return diagnosticRecords; } + private static bool PipelineIsFollowedByNewlineOrLineContinuation(Token[] tokens, int startIndex) + { + if (startIndex >= tokens.Length - 1) + { + return false; + } + + Token nextToken = null; + for (int i = startIndex + 1; i < tokens.Length; i++) + { + nextToken = tokens[i]; + + switch (nextToken.Kind) + { + case TokenKind.Comment: + continue; + + case TokenKind.NewLine: + case TokenKind.LineContinuation: + return true; + + default: + return false; + } + } + + // We've run out of tokens but haven't seen a newline + return false; + } + private static bool LineHasPipelineBeforeToken(Token[] tokens, int tokenIndex, Token token) { int searchIndex = tokenIndex; diff --git a/Tests/Rules/UseConsistentIndentation.tests.ps1 b/Tests/Rules/UseConsistentIndentation.tests.ps1 index 06dbea290..3f527b2f0 100644 --- a/Tests/Rules/UseConsistentIndentation.tests.ps1 +++ b/Tests/Rules/UseConsistentIndentation.tests.ps1 @@ -156,6 +156,18 @@ foo | Invoke-FormatterAssertion $scriptDefinition $expected 3 $settings } + It "When a comment is after a pipeline and before the newline " { + $scriptDefinition = @' +foo | # comment +bar +'@ + $expected = @' +foo | # comment + bar +'@ + Invoke-FormatterAssertion $scriptDefinition $expected 1 $settings + } + It "Should find a violation if a pipleline element is not indented correctly" { $def = @' get-process |