Skip to content

Commit

Permalink
Fix PSCloseBrace rule to not wrongly flag closing brace of one-line h…
Browse files Browse the repository at this point in the history
…ashtable, 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>
  • Loading branch information
bergmeister and rjmholt authored Aug 19, 2019
1 parent 171c81d commit 4f82d81
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
12 changes: 11 additions & 1 deletion Engine/TokenOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public IEnumerable<Token> GetCloseBracesInCommandElements()
public IEnumerable<Tuple<Token, Token>> GetBracePairs()
{
var openBraceStack = new Stack<Token>();
IEnumerable<Ast> hashtableAsts = ast.FindAll(oneAst => oneAst is HashtableAst, searchNestedScriptBlocks: true);
foreach (var token in tokens)
{
if (token.Kind == TokenKind.LCurly)
Expand All @@ -84,7 +85,16 @@ public IEnumerable<Tuple<Token, Token>> GetBracePairs()
if (token.Kind == TokenKind.RCurly
&& openBraceStack.Count > 0)
{
yield return new Tuple<Token, Token>(openBraceStack.Pop(), token);
bool closeBraceBelongsToHashTable = hashtableAsts.Any(hashtableAst =>
{
return hashtableAst.Extent.EndLineNumber == token.Extent.EndLineNumber
&& hashtableAst.Extent.EndColumnNumber == token.Extent.EndColumnNumber;
});

if (!closeBraceBelongsToHashTable)
{
yield return new Tuple<Token, Token>(openBraceStack.Pop(), token);
}
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions Tests/Rules/PlaceCloseBrace.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,18 @@ $hashtable = @{a = 1; b = 2}
}
}

Context "When there is a one line hashtable inside a one line statement" {
BeforeAll {
$scriptDefinition = 'if ($true) { $test = @{ } }'
$ruleConfiguration.'IgnoreOneLineBlock' = $true
}

It "Should not find a violation" {
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDefinition -Settings $settings
$violations.Count | Should -Be 0
}
}

Context "When there is a multi-line hashtable" {
BeforeAll {

Expand Down

0 comments on commit 4f82d81

Please sign in to comment.