Skip to content

Commit ac68598

Browse files
committed
fix: #1561
1 parent deb3512 commit ac68598

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Rules/UseConsistentWhitespace.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,11 +556,32 @@ private IEnumerable<DiagnosticRecord> FindParameterViolations(Ast ast)
556556
{
557557
IScriptExtent leftExtent = commandParameterAstElements[i].Extent;
558558
IScriptExtent rightExtent = commandParameterAstElements[i + 1].Extent;
559+
560+
// Skip if elements are on different lines
559561
if (leftExtent.EndLineNumber != rightExtent.StartLineNumber)
560562
{
561563
continue;
562564
}
563565

566+
// # 1561 - Skip if the whitespace is inside a string literal
567+
// Check if any string in the command contains this whitespace region
568+
var stringAsts = commandAst.FindAll(a => a is StringConstantExpressionAst || a is ExpandableStringExpressionAst, true);
569+
bool isInsideString = false;
570+
foreach (var stringAst in stringAsts)
571+
{
572+
if (stringAst.Extent.StartOffset < leftExtent.EndOffset &&
573+
stringAst.Extent.EndOffset > rightExtent.StartOffset)
574+
{
575+
isInsideString = true;
576+
break;
577+
}
578+
}
579+
580+
if (isInsideString)
581+
{
582+
continue;
583+
}
584+
564585
var expectedStartColumnNumberOfRightExtent = leftExtent.EndColumnNumber + 1;
565586
if (rightExtent.StartColumnNumber > expectedStartColumnNumberOfRightExtent)
566587
{

Tests/Rules/UseConsistentWhitespace.tests.ps1

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,27 @@ bar -h i `
681681
Invoke-Formatter -ScriptDefinition $def -Settings $settings |
682682
Should -Be $expected
683683
}
684+
685+
# Tests for #1561
686+
It "Should not remove whitespace inside string literals" {
687+
$def = @'
688+
$InputList | ForEach-Object {
689+
$_.Name
690+
} | Select-Object -First 2 | Join-String -sep ", " -OutputPrefix 'Results: '
691+
'@
692+
$expected = @'
693+
$InputList | ForEach-Object {
694+
$_.Name
695+
} | Select-Object -First 2 | Join-String -sep ", " -OutputPrefix 'Results: '
696+
'@
697+
Invoke-Formatter -ScriptDefinition $def -Settings $settings | Should -BeExactly $expected
698+
}
699+
700+
It "Should not remove whitespace from string parameters with multiple arguments" {
701+
$def = 'Get-Process | Out-String -Stream | Select-String -Pattern "chrome", "firefox" -SimpleMatch'
702+
$expected = 'Get-Process | Out-String -Stream | Select-String -Pattern "chrome", "firefox" -SimpleMatch'
703+
Invoke-Formatter -ScriptDefinition $def -Settings $settings | Should -BeExactly $expected
704+
}
684705
}
685706

686707
Context "When keywords follow closing braces" {

0 commit comments

Comments
 (0)