diff --git a/Rules/UseConsistentIndentation.cs b/Rules/UseConsistentIndentation.cs index 06724c3b7..7b8ba51a4 100644 --- a/Rules/UseConsistentIndentation.cs +++ b/Rules/UseConsistentIndentation.cs @@ -220,16 +220,25 @@ public override IEnumerable AnalyzeScript(Ast ast, string file // Check if the current token matches the end of a PipelineAst var matchingPipeLineAstEnd = pipelineAsts.FirstOrDefault(pipelineAst => PositionIsEqual(pipelineAst.Extent.EndScriptPosition, token.Extent.EndScriptPosition)) as PipelineAst; - if (matchingPipeLineAstEnd != null) + + if (matchingPipeLineAstEnd == null) { - if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationForFirstPipeline) - { - indentationLevel = ClipNegative(indentationLevel - 1); - } - else if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationAfterEveryPipeline) - { - indentationLevel = ClipNegative(indentationLevel - (matchingPipeLineAstEnd.PipelineElements.Count - 1)); - } + continue; + } + + bool pipelineSpansOnlyOneLine = matchingPipeLineAstEnd.Extent.StartLineNumber == matchingPipeLineAstEnd.Extent.EndLineNumber; + if (pipelineSpansOnlyOneLine) + { + continue; + } + + if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationForFirstPipeline) + { + indentationLevel = ClipNegative(indentationLevel - 1); + } + else if (pipelineIndentationStyle == PipelineIndentationStyle.IncreaseIndentationAfterEveryPipeline) + { + indentationLevel = ClipNegative(indentationLevel - (matchingPipeLineAstEnd.PipelineElements.Count - 1)); } } diff --git a/Tests/Rules/UseConsistentIndentation.tests.ps1 b/Tests/Rules/UseConsistentIndentation.tests.ps1 index 408423dc7..986b900e8 100644 --- a/Tests/Rules/UseConsistentIndentation.tests.ps1 +++ b/Tests/Rules/UseConsistentIndentation.tests.ps1 @@ -174,6 +174,23 @@ baz Test-CorrectionExtentFromContent @params } + It "Should preserve script when using PipelineIndentation " -TestCases @( + @{ PipelineIndentation = 'IncreaseIndentationForFirstPipeline' } + @{ PipelineIndentation = 'IncreaseIndentationAfterEveryPipeline' } + @{ PipelineIndentation = 'NoIndentation' } + ) { + param ($PipelineIndentation) + $idempotentScriptDefinition = @' +function hello { + if ($true) { + "hello" | Out-Host + } +} +'@ + $settings.Rules.PSUseConsistentIndentation.PipelineIndentation = $PipelineIndentation + Invoke-Formatter -ScriptDefinition $idempotentScriptDefinition -Settings $settings | Should -Be $idempotentScriptDefinition + } + It "Should indent pipelines correctly using NoIndentation option" { $def = @' foo |