Skip to content

Fix indentation for multi-line pipelines #705

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

Merged
merged 4 commits into from
Feb 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion Rules/UseConsistentIndentation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,23 @@ public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string file
// we add this redundant check
if (onNewLine)
{
AddViolation(token, indentationLevel, diagnosticRecords, ref onNewLine);
var tempIndentationLevel = indentationLevel;

// Ignore comments
// Since the previous token is a newline token we start
// looking for comments at the token before the newline token.
int j = k - 2;
while (j > 0 && tokens[j].Kind == TokenKind.Comment)
{
--j;
}

if (j >= 0 && tokens[j].Kind == TokenKind.Pipe)
{
++tempIndentationLevel;
}

AddViolation(token, tempIndentationLevel, diagnosticRecords, ref onNewLine);
}
break;
}
Expand Down
31 changes: 31 additions & 0 deletions Tests/Rules/UseConsistentIndentation.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,35 @@ function foo {
$violations.Count | Should Be 0
}
}

Context "When a multi-line command is given" {
It "Should find a violation if a pipleline element is not indented correctly" {
$def = @'
get-process |
where-object {$_.Name -match 'powershell'}
'@
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
$violations.Count | Should Be 1
}

It "Should not find a violation if a pipleline element is indented correctly" {
$def = @'
get-process |
where-object {$_.Name -match 'powershell'}
'@
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
$violations.Count | Should Be 0
}

It "Should ignore comment in the pipleline" {
$def = @'
get-process |
where-object Name -match 'powershell' | # only this is indented correctly
select Name,Id |
format-list
'@
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
$violations.Count | Should Be 3
}
}
}