Skip to content
Merged
15 changes: 10 additions & 5 deletions Rules/UseConsistentIndentation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,20 @@ public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string file
{
++tempIndentationLevel;
}
else

// check for comments in between multi-line commands with line continuation
if (k > 2 && tokens[k - 1].Kind == TokenKind.NewLine
&& tokens[k - 2].Kind == TokenKind.Comment)
{
// 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;
j--;
}

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

Expand Down
51 changes: 51 additions & 0 deletions Tests/Rules/UseConsistentIndentation.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,25 @@ $testRootDirectory = Split-Path -Parent $directory

Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1")


Describe "UseConsistentIndentation" {
BeforeAll {
function Invoke-FormatterAssertion {
param(
[string] $ScriptDefinition,
[string] $ExcpectedScriptDefinition,
[int] $NumberOfExpectedWarnings,
[hashtable] $Settings
)

# Unit test just using this rule only
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -Settings $settings
$violations.Count | Should -Be $NumberOfExpectedWarnings -Because $ScriptDefinition
Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings | Should -Be $expected -Because $ScriptDefinition
# Integration test with all default formatting rules
Invoke-Formatter -ScriptDefinition $scriptDefinition | Should -Be $expected -Because $ScriptDefinition
}
}
BeforeEach {
$indentationUnit = ' '
$indentationSize = 4
Expand Down Expand Up @@ -107,6 +125,39 @@ function foo {
}

Context "When a multi-line command is given" {

It "When a comment is in the middle of a multi-line statement with preceding and succeeding line continuations" {
$scriptDefinition = @'
foo `
# comment
-bar `
-baz
'@
$expected = @'
foo `
# comment
-bar `
-baz
'@
Invoke-FormatterAssertion $scriptDefinition $expected 3 $settings
}

It "When a comment is in the middle of a multi-line statement with preceding pipeline and succeeding line continuation " {
$scriptDefinition = @'
foo |
# comment
bar `
-baz
'@
$expected = @'
foo |
# comment
bar `
-baz
'@
Invoke-FormatterAssertion $scriptDefinition $expected 3 $settings
}

It "Should find a violation if a pipleline element is not indented correctly" {
$def = @'
get-process |
Expand Down