Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UseConsistentIndentation: When non-default options are used, cater for the case of a comment between pipe and newline #1463

34 changes: 32 additions & 2 deletions Rules/UseConsistentIndentation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ public override IEnumerable<DiagnosticRecord> 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;
Expand Down Expand Up @@ -254,6 +254,36 @@ public override IEnumerable<DiagnosticRecord> 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;
Expand Down
12 changes: 12 additions & 0 deletions Tests/Rules/UseConsistentIndentation.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down