Skip to content

Commit

Permalink
PSAvoidTrailingWhitespace: Rule not applied when using formatter + si…
Browse files Browse the repository at this point in the history
…ngle character lines with trailing whitespace are truncated (#1993)

* Formatter: Added PSAvoidTrailingWhitespace to the list of rules considered by the formatter

* Rules/AvoidTrailingWhitespace: Fixed issue where lines with a single character, followed by multiple white-spaces were truncated when fixed/formatted

* Tests/Rules/AvoidTrailingWhitespace: Added test for usage of Invoke-Formatter with PSAvoidTrailingWhitespace and also checking that single-character lines that have trailing whitespace are not removed

---------

Co-authored-by: Christoph Bergmeister <[email protected]>
  • Loading branch information
liamjpeters and bergmeister authored Feb 25, 2025
1 parent 4f0c07a commit d6eb35e
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions Engine/Formatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public static string Format<TCmdlet>(
"PSAvoidUsingDoubleQuotesForConstantString",
"PSAvoidSemicolonsAsLineTerminators",
"PSAvoidExclaimOperator",
"PSAvoidTrailingWhitespace",
};

var text = new EditableText(scriptDefinition);
Expand Down
2 changes: 1 addition & 1 deletion Rules/AvoidTrailingWhitespace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
}

int startColumnOfTrailingWhitespace = 1;
for (int i = line.Length - 2; i > 0; i--)
for (int i = line.Length - 2; i >= 0; i--)
{
if (line[i] != ' ' && line[i] != '\t')
{
Expand Down
25 changes: 25 additions & 0 deletions Tests/Rules/AvoidTrailingWhitespace.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ BeforeAll {

$settings = @{
IncludeRules = @($ruleName)
Rules = @{
$ruleName = @{}
}
}
}

Expand All @@ -34,4 +37,26 @@ Describe "AvoidTrailingWhitespace" {
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
Test-CorrectionExtentFromContent $def $violations 1 $Whitespace ''
}

It 'Should be used by Invoke-Formatter, when in settings, replacing trailing <Type>' -TestCases $testCases {
param (
[string] $Whitespace
)
# Test also guards against regression where single-character lines, with trailing whitespace
# would be removed entirely. See issues #1757, #1992
$def = @"
Function Get-Example {
'Example'$Whitespace
}$Whitespace
"@

$expected = @"
Function Get-Example {
'Example'
}
"@
$formatted = Invoke-Formatter -ScriptDefinition $def -Settings $settings
$formatted | Should -Be $expected
}

}

0 comments on commit d6eb35e

Please sign in to comment.