Skip to content

Commit d6eb35e

Browse files
PSAvoidTrailingWhitespace: Rule not applied when using formatter + single 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 <c.bergmeister@gmail.com>
1 parent 4f0c07a commit d6eb35e

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

Diff for: Engine/Formatter.cs

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ public static string Format<TCmdlet>(
4747
"PSAvoidUsingDoubleQuotesForConstantString",
4848
"PSAvoidSemicolonsAsLineTerminators",
4949
"PSAvoidExclaimOperator",
50+
"PSAvoidTrailingWhitespace",
5051
};
5152

5253
var text = new EditableText(scriptDefinition);

Diff for: Rules/AvoidTrailingWhitespace.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
5454
}
5555

5656
int startColumnOfTrailingWhitespace = 1;
57-
for (int i = line.Length - 2; i > 0; i--)
57+
for (int i = line.Length - 2; i >= 0; i--)
5858
{
5959
if (line[i] != ' ' && line[i] != '\t')
6060
{

Diff for: Tests/Rules/AvoidTrailingWhitespace.tests.ps1

+25
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ BeforeAll {
99

1010
$settings = @{
1111
IncludeRules = @($ruleName)
12+
Rules = @{
13+
$ruleName = @{}
14+
}
1215
}
1316
}
1417

@@ -34,4 +37,26 @@ Describe "AvoidTrailingWhitespace" {
3437
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
3538
Test-CorrectionExtentFromContent $def $violations 1 $Whitespace ''
3639
}
40+
41+
It 'Should be used by Invoke-Formatter, when in settings, replacing trailing <Type>' -TestCases $testCases {
42+
param (
43+
[string] $Whitespace
44+
)
45+
# Test also guards against regression where single-character lines, with trailing whitespace
46+
# would be removed entirely. See issues #1757, #1992
47+
$def = @"
48+
Function Get-Example {
49+
'Example'$Whitespace
50+
}$Whitespace
51+
"@
52+
53+
$expected = @"
54+
Function Get-Example {
55+
'Example'
3756
}
57+
"@
58+
$formatted = Invoke-Formatter -ScriptDefinition $def -Settings $settings
59+
$formatted | Should -Be $expected
60+
}
61+
62+
}

0 commit comments

Comments
 (0)