From 0620491a53902e79318cec741f84ef097b81aa27 Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Sat, 4 May 2019 13:17:31 +0100 Subject: [PATCH 1/2] Prevent crash if hashtable definition start on first token and there is a PSCloseBrace violation --- Rules/PlaceCloseBrace.cs | 2 +- Tests/Rules/PlaceCloseBrace.tests.ps1 | 24 ++++++++++++++++++------ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Rules/PlaceCloseBrace.cs b/Rules/PlaceCloseBrace.cs index d9df57c75..652197afd 100644 --- a/Rules/PlaceCloseBrace.cs +++ b/Rules/PlaceCloseBrace.cs @@ -288,7 +288,7 @@ private string GetIndentation(Token[] tokens, int closeBracePos, int openBracePo { // if open brace on a new line by itself, use its indentation var openBraceToken = tokens[openBracePos]; - if (tokens[openBracePos - 1].Kind == TokenKind.NewLine) + if (openBracePos > 0 && tokens[openBracePos - 1].Kind == TokenKind.NewLine) { return new String(' ', openBraceToken.Extent.StartColumnNumber - 1); } diff --git a/Tests/Rules/PlaceCloseBrace.tests.ps1 b/Tests/Rules/PlaceCloseBrace.tests.ps1 index d9e6dda0a..fd9e354a2 100644 --- a/Tests/Rules/PlaceCloseBrace.tests.ps1 +++ b/Tests/Rules/PlaceCloseBrace.tests.ps1 @@ -80,19 +80,31 @@ $hashtable = @{a = 1; b = 2} Context "When there is a multi-line hashtable" { BeforeAll { - $def = @' -$hashtable = @{ - a = 1 - b = 2} -'@ + $ruleConfiguration.'NoEmptyLineBefore' = $false $ruleConfiguration.'IgnoreOneLineBlock' = $true $ruleConfiguration.'NewLineAfter' = $false - $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings } It "Should find a violation" { + $def = @' + $hashtable = @{ + a = 1 + b = 2} +'@ + $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings + $violations.Count | Should -Be 1 + } + + It "Should not crash when hashtable is defined on first token" { + $def = @' + @{ + key = value } +'@ + + $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings -ErrorAction Stop $violations.Count | Should -Be 1 + Invoke-Formatter -ScriptDefinition $def -ErrorAction Stop } } From 098139f9d7ac3d8f9c3f8ab65f4d3854489fbe8a Mon Sep 17 00:00:00 2001 From: Christoph Bergmeister Date: Wed, 5 Jun 2019 19:46:05 +0100 Subject: [PATCH 2/2] improve test as per PR review --- Tests/Rules/PlaceCloseBrace.tests.ps1 | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Tests/Rules/PlaceCloseBrace.tests.ps1 b/Tests/Rules/PlaceCloseBrace.tests.ps1 index fd9e354a2..22d4785f6 100644 --- a/Tests/Rules/PlaceCloseBrace.tests.ps1 +++ b/Tests/Rules/PlaceCloseBrace.tests.ps1 @@ -97,10 +97,7 @@ $hashtable = @{a = 1; b = 2} } It "Should not crash when hashtable is defined on first token" { - $def = @' - @{ - key = value } -'@ + $def = "@{ `n Key = value }" $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings -ErrorAction Stop $violations.Count | Should -Be 1