Skip to content

Commit f99ae8f

Browse files
author
Kapil Borle
authored
Merge pull request #705 from PowerShell/kapilmb/indentation-rule-exception
Fix indentation for multi-line pipelines
2 parents 511ee68 + 5be0cdd commit f99ae8f

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

Rules/UseConsistentIndentation.cs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,23 @@ public override IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string file
9999
// we add this redundant check
100100
if (onNewLine)
101101
{
102-
AddViolation(token, indentationLevel, diagnosticRecords, ref onNewLine);
102+
var tempIndentationLevel = indentationLevel;
103+
104+
// Ignore comments
105+
// Since the previous token is a newline token we start
106+
// looking for comments at the token before the newline token.
107+
int j = k - 2;
108+
while (j > 0 && tokens[j].Kind == TokenKind.Comment)
109+
{
110+
--j;
111+
}
112+
113+
if (j >= 0 && tokens[j].Kind == TokenKind.Pipe)
114+
{
115+
++tempIndentationLevel;
116+
}
117+
118+
AddViolation(token, tempIndentationLevel, diagnosticRecords, ref onNewLine);
103119
}
104120
break;
105121
}

Tests/Rules/UseConsistentIndentation.tests.ps1

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,35 @@ function foo {
113113
$violations.Count | Should Be 0
114114
}
115115
}
116+
117+
Context "When a multi-line command is given" {
118+
It "Should find a violation if a pipleline element is not indented correctly" {
119+
$def = @'
120+
get-process |
121+
where-object {$_.Name -match 'powershell'}
122+
'@
123+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
124+
$violations.Count | Should Be 1
125+
}
126+
127+
It "Should not find a violation if a pipleline element is indented correctly" {
128+
$def = @'
129+
get-process |
130+
where-object {$_.Name -match 'powershell'}
131+
'@
132+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
133+
$violations.Count | Should Be 0
134+
}
135+
136+
It "Should ignore comment in the pipleline" {
137+
$def = @'
138+
get-process |
139+
where-object Name -match 'powershell' | # only this is indented correctly
140+
select Name,Id |
141+
format-list
142+
'@
143+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
144+
$violations.Count | Should Be 3
145+
}
146+
}
116147
}

0 commit comments

Comments
 (0)