Skip to content

Commit d1a1bcb

Browse files
authored
PSUseConsistentWhitespace: Handle redirect operators which are not in stream order (#2001)
1 parent b5fec0a commit d1a1bcb

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Rules/UseConsistentWhitespace.cs

+10-1
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,17 @@ private IEnumerable<DiagnosticRecord> FindParameterViolations(Ast ast)
396396
testAst => testAst is CommandAst, true);
397397
foreach (CommandAst commandAst in commandAsts)
398398
{
399+
/// When finding all the command parameter elements, there is no guarantee that
400+
/// we will read them from the AST in the order they appear in the script (in token
401+
/// order). So we first sort the tokens by their starting line number, followed by
402+
/// their starting column number.
399403
List<Ast> commandParameterAstElements = commandAst.FindAll(
400-
testAst => testAst.Parent == commandAst, searchNestedScriptBlocks: false).ToList();
404+
testAst => testAst.Parent == commandAst, searchNestedScriptBlocks: false
405+
).OrderBy(
406+
e => e.Extent.StartLineNumber
407+
).ThenBy(
408+
e => e.Extent.StartColumnNumber
409+
).ToList();
401410
for (int i = 0; i < commandParameterAstElements.Count - 1; i++)
402411
{
403412
IScriptExtent leftExtent = commandParameterAstElements[i].Extent;

Tests/Rules/UseConsistentWhitespace.tests.ps1

+14
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,12 @@ bar -h i `
540540
Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings | Should -Be $null
541541
}
542542

543+
It "Should not find a violation when redirect operators, spearated by 1 space, are used and not in stream order" {
544+
# Related to Issue #2000
545+
$def = 'foo 3>&1 1>$null 2>&1'
546+
Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings | Should -Be $null
547+
}
548+
543549
It "Should find 1 violation if there is 1 space too much before a parameter" {
544550
$def = 'foo -bar'
545551
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
@@ -578,5 +584,13 @@ bar -h i `
578584
Invoke-Formatter -ScriptDefinition "$def" -Settings $settings |
579585
Should -Be "$expected"
580586
}
587+
588+
It "Should fix script when redirects are involved and whitespace is not consistent" {
589+
# Related to Issue #2000
590+
$def = 'foo 3>&1 1>$null 2>&1'
591+
$expected = 'foo 3>&1 1>$null 2>&1'
592+
Invoke-Formatter -ScriptDefinition $def -Settings $settings |
593+
Should -Be $expected
594+
}
581595
}
582596
}

0 commit comments

Comments
 (0)