diff --git a/RuleDocumentation/UseConsistentWhitespace.md b/RuleDocumentation/UseConsistentWhitespace.md index 6fa553b00..192f7441a 100644 --- a/RuleDocumentation/UseConsistentWhitespace.md +++ b/RuleDocumentation/UseConsistentWhitespace.md @@ -38,7 +38,7 @@ Checks if there is space between a keyword and its corresponding open parenthesi #### CheckOperator: bool (Default value is `$true`) -Checks if a binary operator is surrounded on both sides by a space. E.g. `$x = 1`. +Checks if a binary or unary operator is surrounded on both sides by a space. E.g. `$x = 1`. #### CheckSeparator: bool (Default value is `$true`) diff --git a/Rules/UseConsistentWhitespace.cs b/Rules/UseConsistentWhitespace.cs index 180bfb798..12a47dfbd 100644 --- a/Rules/UseConsistentWhitespace.cs +++ b/Rules/UseConsistentWhitespace.cs @@ -307,6 +307,14 @@ private IEnumerable FindOperatorViolations(TokenOperations tok continue; } + // exclude unary operator for cases like $foo.bar(-$Var) + if (TokenTraits.HasTrait(tokenNode.Value.Kind, TokenFlags.UnaryOperator) && + tokenNode.Previous.Value.Kind == TokenKind.LParen && + tokenNode.Next.Value.Kind == TokenKind.Variable) + { + continue; + } + var hasWhitespaceBefore = IsPreviousTokenOnSameLineAndApartByWhitespace(tokenNode); var hasWhitespaceAfter = tokenNode.Next.Value.Kind == TokenKind.NewLine || IsPreviousTokenOnSameLineAndApartByWhitespace(tokenNode.Next); diff --git a/Tests/Engine/InvokeFormatter.tests.ps1 b/Tests/Engine/InvokeFormatter.tests.ps1 index 86543e09c..5c0e54a88 100644 --- a/Tests/Engine/InvokeFormatter.tests.ps1 +++ b/Tests/Engine/InvokeFormatter.tests.ps1 @@ -30,6 +30,15 @@ function foo { Invoke-Formatter $def $settings | Should -Be $expected } + + It "Should not expand unary operators when being used as a single negative argument" { + $script = '$foo.bar(-$a)' + Invoke-Formatter '$foo.bar(-$a)' -Settings CodeFormatting | Should -Be $script + } + + It "Should expand unary operators when not being used as a single negative argument" { + Invoke-Formatter '$foo.bar(-$a+$b+$c)' -Settings CodeFormatting | Should -Be '$foo.bar(-$a + $b + $c)' + } } Context "When a range is given" {