Skip to content

Commit

Permalink
PSUseConsistentWhitespace: Handle redirect operators which are not in…
Browse files Browse the repository at this point in the history
… stream order (#2001)
  • Loading branch information
liamjpeters authored Jul 16, 2024
1 parent b5fec0a commit d1a1bcb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
11 changes: 10 additions & 1 deletion Rules/UseConsistentWhitespace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,17 @@ private IEnumerable<DiagnosticRecord> FindParameterViolations(Ast ast)
testAst => testAst is CommandAst, true);
foreach (CommandAst commandAst in commandAsts)
{
/// When finding all the command parameter elements, there is no guarantee that
/// we will read them from the AST in the order they appear in the script (in token
/// order). So we first sort the tokens by their starting line number, followed by
/// their starting column number.
List<Ast> commandParameterAstElements = commandAst.FindAll(
testAst => testAst.Parent == commandAst, searchNestedScriptBlocks: false).ToList();
testAst => testAst.Parent == commandAst, searchNestedScriptBlocks: false
).OrderBy(
e => e.Extent.StartLineNumber
).ThenBy(
e => e.Extent.StartColumnNumber
).ToList();
for (int i = 0; i < commandParameterAstElements.Count - 1; i++)
{
IScriptExtent leftExtent = commandParameterAstElements[i].Extent;
Expand Down
14 changes: 14 additions & 0 deletions Tests/Rules/UseConsistentWhitespace.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,12 @@ bar -h i `
Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings | Should -Be $null
}

It "Should not find a violation when redirect operators, spearated by 1 space, are used and not in stream order" {
# Related to Issue #2000
$def = 'foo 3>&1 1>$null 2>&1'
Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings | Should -Be $null
}

It "Should find 1 violation if there is 1 space too much before a parameter" {
$def = 'foo -bar'
$violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
Expand Down Expand Up @@ -578,5 +584,13 @@ bar -h i `
Invoke-Formatter -ScriptDefinition "$def" -Settings $settings |
Should -Be "$expected"
}

It "Should fix script when redirects are involved and whitespace is not consistent" {
# Related to Issue #2000
$def = 'foo 3>&1 1>$null 2>&1'
$expected = 'foo 3>&1 1>$null 2>&1'
Invoke-Formatter -ScriptDefinition $def -Settings $settings |
Should -Be $expected
}
}
}

0 comments on commit d1a1bcb

Please sign in to comment.