Skip to content

Commit 4f82d81

Browse files
bergmeisterrjmholt
andauthored
Fix PSCloseBrace rule to not wrongly flag closing brace of one-line hashtable, which lead to incorrect formatting (#1309)
* Ignore Hashtables for PlaceCloseBrace rule * suppress only single line hash tables * Add test and make fix in proper place where RCurly of hashtable gets wrongly associated to the LCurly of the one line if statement * cleanup code * revert change to minimise diff * final cleanup * Apply suggestions from code review Co-Authored-By: Robert Holt <rjmholt@gmail.com>
1 parent 171c81d commit 4f82d81

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

Engine/TokenOperations.cs

+11-1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ public IEnumerable<Token> GetCloseBracesInCommandElements()
7373
public IEnumerable<Tuple<Token, Token>> GetBracePairs()
7474
{
7575
var openBraceStack = new Stack<Token>();
76+
IEnumerable<Ast> hashtableAsts = ast.FindAll(oneAst => oneAst is HashtableAst, searchNestedScriptBlocks: true);
7677
foreach (var token in tokens)
7778
{
7879
if (token.Kind == TokenKind.LCurly)
@@ -84,7 +85,16 @@ public IEnumerable<Tuple<Token, Token>> GetBracePairs()
8485
if (token.Kind == TokenKind.RCurly
8586
&& openBraceStack.Count > 0)
8687
{
87-
yield return new Tuple<Token, Token>(openBraceStack.Pop(), token);
88+
bool closeBraceBelongsToHashTable = hashtableAsts.Any(hashtableAst =>
89+
{
90+
return hashtableAst.Extent.EndLineNumber == token.Extent.EndLineNumber
91+
&& hashtableAst.Extent.EndColumnNumber == token.Extent.EndColumnNumber;
92+
});
93+
94+
if (!closeBraceBelongsToHashTable)
95+
{
96+
yield return new Tuple<Token, Token>(openBraceStack.Pop(), token);
97+
}
8898
}
8999
}
90100
}

Tests/Rules/PlaceCloseBrace.tests.ps1

+12
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,18 @@ $hashtable = @{a = 1; b = 2}
7878
}
7979
}
8080

81+
Context "When there is a one line hashtable inside a one line statement" {
82+
BeforeAll {
83+
$scriptDefinition = 'if ($true) { $test = @{ } }'
84+
$ruleConfiguration.'IgnoreOneLineBlock' = $true
85+
}
86+
87+
It "Should not find a violation" {
88+
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -Settings $settings
89+
$violations.Count | Should -Be 0
90+
}
91+
}
92+
8193
Context "When there is a multi-line hashtable" {
8294
BeforeAll {
8395

0 commit comments

Comments
 (0)