diff --git a/Engine/Commands/InvokeFormatterCommand.cs b/Engine/Commands/InvokeFormatterCommand.cs index d9df017fa..3d1179e20 100644 --- a/Engine/Commands/InvokeFormatterCommand.cs +++ b/Engine/Commands/InvokeFormatterCommand.cs @@ -5,9 +5,11 @@ using System.Collections.Generic; using System.IO; using System.Globalization; +using System.Linq; using System.Text; using System.Management.Automation; using System.Management.Automation.Language; +using Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands { @@ -239,7 +241,7 @@ private static string GetIndentationKind(string scriptDefinition) int spaceIndentedLines = 0; string firstIndentationKind = "space"; bool foundIndentation = false; - string[] lines = scriptDefinition.Split('\n'); + string[] lines = scriptDefinition.GetLines().ToArray(); Parser.ParseInput(scriptDefinition, out Token[] tokens, out ParseError[] errors); var countedLines = new HashSet(); diff --git a/Engine/Extensions.cs b/Engine/Extensions.cs index 46b67bf65..3402021e2 100644 --- a/Engine/Extensions.cs +++ b/Engine/Extensions.cs @@ -18,7 +18,7 @@ public static class Extensions /// public static IEnumerable GetLines(this string text) { - return text.Split('\n').Select(line => line.TrimEnd('\r')); + return text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); } /// diff --git a/Tests/Engine/InvokeFormatter.tests.ps1 b/Tests/Engine/InvokeFormatter.tests.ps1 index 3d5bcf9b6..d9b990285 100644 --- a/Tests/Engine/InvokeFormatter.tests.ps1 +++ b/Tests/Engine/InvokeFormatter.tests.ps1 @@ -54,10 +54,22 @@ Describe "Invoke-Formatter Cmdlet" { [System.IO.File]::ReadAllBytes($path)[0..1] | Should -Be @(255, 254) } + It 'Formats a file with CR-only line endings' { + $path = Join-Path $TestDrive 'cr-only.ps1' + $scriptDefinition = "function foo {`r`t`$x=1`r}" + $expected = "function foo {`r`t`$x = 1`r}" + [System.IO.File]::WriteAllText($path, $scriptDefinition) + + Invoke-Formatter -Path $path | Should -Be $expected + + [System.IO.File]::ReadAllText($path) | Should -Be $expected + } + It 'Best-effort formats BOM-less files using a legacy encoding' { $path = Join-Path $TestDrive 'legacy-encoding.ps1' - $scriptDefinition = '$name=''café''' - $expected = '$name = ''café''' + $cafe = 'caf' + [char]0xE9 + $scriptDefinition = "`$name='$cafe'" + $expected = "`$name = '$cafe'" $encoding = [System.Text.Encoding]::GetEncoding(1252) [System.IO.File]::WriteAllBytes($path, $encoding.GetBytes($scriptDefinition))