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

19 changes: 17 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,21 @@ public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string file
return diagnosticRecords;
}

private static bool PipelineIsFollowedByNewlineOrLineContinuation(Token[] tokens, int tokenIndex)
{
if (tokenIndex == tokens.Length - 1)
{
return false;
}
var nextToken = tokens[tokenIndex + 1];
if (nextToken.Kind == TokenKind.Comment && tokenIndex < tokens.Length - 2)
{
nextToken = tokens[tokenIndex + 2];
}
return nextToken.Kind == TokenKind.NewLine ||
nextToken.Kind == TokenKind.LineContinuation;
}
bergmeister marked this conversation as resolved.
Show resolved Hide resolved

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