Skip to content

Commit 00c4787

Browse files
authored
Tweak UseConsistentWhitespace formatting rule to exclude first unary operator when being used in argument (#949)
* exclude unary operator form UseConsistentWhitespace rule * fix failing test by being more precise about the use case of the unary operator enhancement * add test and docs * tweak fix to only apply to first argument * Fix accidental space in test expectation
1 parent d1bec74 commit 00c4787

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

RuleDocumentation/UseConsistentWhitespace.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ Checks if there is space between a keyword and its corresponding open parenthesi
3838

3939
#### CheckOperator: bool (Default value is `$true`)
4040

41-
Checks if a binary operator is surrounded on both sides by a space. E.g. `$x = 1`.
41+
Checks if a binary or unary operator is surrounded on both sides by a space. E.g. `$x = 1`.
4242

4343
#### CheckSeparator: bool (Default value is `$true`)
4444

Rules/UseConsistentWhitespace.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,14 @@ private IEnumerable<DiagnosticRecord> FindOperatorViolations(TokenOperations tok
307307
continue;
308308
}
309309

310+
// exclude unary operator for cases like $foo.bar(-$Var)
311+
if (TokenTraits.HasTrait(tokenNode.Value.Kind, TokenFlags.UnaryOperator) &&
312+
tokenNode.Previous.Value.Kind == TokenKind.LParen &&
313+
tokenNode.Next.Value.Kind == TokenKind.Variable)
314+
{
315+
continue;
316+
}
317+
310318
var hasWhitespaceBefore = IsPreviousTokenOnSameLineAndApartByWhitespace(tokenNode);
311319
var hasWhitespaceAfter = tokenNode.Next.Value.Kind == TokenKind.NewLine
312320
|| IsPreviousTokenOnSameLineAndApartByWhitespace(tokenNode.Next);

Tests/Engine/InvokeFormatter.tests.ps1

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ function foo {
3030

3131
Invoke-Formatter $def $settings | Should -Be $expected
3232
}
33+
34+
It "Should not expand unary operators when being used as a single negative argument" {
35+
$script = '$foo.bar(-$a)'
36+
Invoke-Formatter '$foo.bar(-$a)' -Settings CodeFormatting | Should -Be $script
37+
}
38+
39+
It "Should expand unary operators when not being used as a single negative argument" {
40+
Invoke-Formatter '$foo.bar(-$a+$b+$c)' -Settings CodeFormatting | Should -Be '$foo.bar(-$a + $b + $c)'
41+
}
3342
}
3443

3544
Context "When a range is given" {

0 commit comments

Comments
 (0)