Skip to content

Commit 853c3d8

Browse files
author
Kapil Borle
authored
Fix violations for one line switch conditionals (#709)
Consider the following expression: switch ($x) { {"a" -eq $_} {"a";break} {"b" -eq $_} {"b";break} } If OnSameLine switch is `on`, this would get formatted to: switch ($x) { {"a" -eq $_} {"a";break} {"b" -eq $_} {"b";break} } With this commit, it ignores these one-line conditional expression and so the output will be the same as the input in this case, i.e., switch ($x) { {"a" -eq $_} {"a";break} {"b" -eq $_} {"b";break} }
1 parent 9ef1119 commit 853c3d8

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

Rules/PlaceOpenBrace.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,8 @@ private IEnumerable<DiagnosticRecord> FindViolationsForBraceShouldBeOnSameLine(
206206
for (int k = 2; k < tokens.Length; k++)
207207
{
208208
if (tokens[k].Kind == TokenKind.LCurly
209-
&& tokens[k - 1].Kind == TokenKind.NewLine)
209+
&& tokens[k - 1].Kind == TokenKind.NewLine
210+
&& !tokensToIgnore.Contains(tokens[k]))
210211
{
211212
yield return new DiagnosticRecord(
212213
GetError(Strings.PlaceOpenBraceErrorShouldBeOnSameLine),

Tests/Rules/PlaceOpenBrace.tests.ps1

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,24 @@ function foo ($param1)
3535
}
3636
}
3737

38+
Context "When an open brace must be on the same line in a switch statement" {
39+
BeforeAll {
40+
$def = @'
41+
switch ($x) {
42+
{"b"} {"b"; break;}
43+
{"a"} {"a"; break;}
44+
}
45+
'@
46+
$ruleConfiguration.'OnSameLine' = $true
47+
$ruleConfiguration.'IgnoreOneLineBlock' = $true
48+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
49+
}
50+
51+
It "Should not find a violation" {
52+
$violations.Count | Should Be 0
53+
}
54+
}
55+
3856
Context "When an open brace must be on a new line" {
3957
BeforeAll {
4058
$def = @'

0 commit comments

Comments
 (0)