From 49cec8d6c9e3677f5299f9f6ff403183a94b9e42 Mon Sep 17 00:00:00 2001 From: Kapil Borle Date: Thu, 9 Feb 2017 14:14:47 -0800 Subject: [PATCH] Fix violations for one line switch conditionals 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} } --- Rules/PlaceOpenBrace.cs | 3 ++- Tests/Rules/PlaceOpenBrace.tests.ps1 | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Rules/PlaceOpenBrace.cs b/Rules/PlaceOpenBrace.cs index 50df9f6c0..eac527f46 100644 --- a/Rules/PlaceOpenBrace.cs +++ b/Rules/PlaceOpenBrace.cs @@ -206,7 +206,8 @@ private IEnumerable FindViolationsForBraceShouldBeOnSameLine( for (int k = 2; k < tokens.Length; k++) { if (tokens[k].Kind == TokenKind.LCurly - && tokens[k - 1].Kind == TokenKind.NewLine) + && tokens[k - 1].Kind == TokenKind.NewLine + && !tokensToIgnore.Contains(tokens[k])) { yield return new DiagnosticRecord( GetError(Strings.PlaceOpenBraceErrorShouldBeOnSameLine), diff --git a/Tests/Rules/PlaceOpenBrace.tests.ps1 b/Tests/Rules/PlaceOpenBrace.tests.ps1 index bbfab27de..4b6126c29 100644 --- a/Tests/Rules/PlaceOpenBrace.tests.ps1 +++ b/Tests/Rules/PlaceOpenBrace.tests.ps1 @@ -35,6 +35,24 @@ function foo ($param1) } } + Context "When an open brace must be on the same line in a switch statement" { + BeforeAll { + $def = @' +switch ($x) { + {"b"} {"b"; break;} + {"a"} {"a"; break;} +} +'@ + $ruleConfiguration.'OnSameLine' = $true + $ruleConfiguration.'IgnoreOneLineBlock' = $true + $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings + } + + It "Should not find a violation" { + $violations.Count | Should Be 0 + } + } + Context "When an open brace must be on a new line" { BeforeAll { $def = @'