Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix LF line-ending auto format bug #10802

Merged
merged 12 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,30 @@ public static bool TryGetSourceLocation(this SourceText text, int line, int char
return false;
}

/// <summary>
/// Applies the set of edits specified, and returns the minimal set needed to make the same changes
/// </summary>
public static TextEdit[] MinimizeTextEdits(this SourceText text, TextEdit[] edits)
=> MinimizeTextEdits(text, edits, out _);

/// <summary>
/// Applies the set of edits specified, and returns the minimal set needed to make the same changes
/// </summary>
public static TextEdit[] MinimizeTextEdits(this SourceText text, TextEdit[] edits, out SourceText originalTextWithChanges)
{
var changes = edits.Select(text.GetTextChange);
originalTextWithChanges = text.WithChanges(changes);

if (text.ContentEquals(originalTextWithChanges))
{
return [];
}

var cleanChanges = SourceTextDiffer.GetMinimalTextChanges(text, originalTextWithChanges, DiffKind.Char);
var cleanEdits = cleanChanges.Select(text.GetTextEdit).ToArray();
return cleanEdits;
}

/// <summary>
/// Determines if the given <see cref="SourceText"/> has more LF line endings ('\n') than CRLF line endings ('\r\n').
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,10 @@ protected async Task<List<TextChange>> AdjustIndentationAsync(FormattingContext
}

var scopeOwner = syntaxTreeRoot.FindInnermostNode(originalLocation);
sourceMappingIndentations[originalLocation] = new IndentationData(indentation);
if (!sourceMappingIndentations.ContainsKey(originalLocation))
{
sourceMappingIndentations[originalLocation] = new IndentationData(indentation);
}

// For @section blocks we have special handling to add a fake source mapping/significant location at the end of the
// section, to return the indentation back to before the start of the section block.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,11 @@ public async Task<TextEdit[]> GetDocumentFormattingEditsAsync(
}

var filteredEdits = range is null
? result.Edits
: result.Edits.Where(e => range.LineOverlapsWith(e.Range));
filteredEdits = NormalizeLineEndings(originalText, filteredEdits);
var minimalEdits = GetMinimalEdits(originalText, filteredEdits);
? result
: result.Where(e => range.LineOverlapsWith(e.Range)).ToArray();

return minimalEdits;
var normalizedEdits = NormalizeLineEndings(originalText, filteredEdits);
return originalText.MinimizeTextEdits(normalizedEdits);
}

public Task<TextEdit[]> GetCSharpOnTypeFormattingEditsAsync(DocumentContext documentContext, RazorFormattingOptions options, int hostDocumentIndex, char triggerCharacter, CancellationToken cancellationToken)
Expand Down Expand Up @@ -248,14 +247,8 @@ internal static TextEdit MergeEdits(TextEdit[] edits, SourceText sourceText)
{
return edits[0];
}
var textChanges = new List<TextChange>();
foreach (var edit in edits)
{
var change = new TextChange(sourceText.GetTextSpan(edit.Range), edit.NewText);
textChanges.Add(change);
}

var changedText = sourceText.WithChanges(textChanges);
var changedText = sourceText.WithChanges(edits.Select(sourceText.GetTextChange));
var affectedRange = changedText.GetEncompassingTextChangeRange(sourceText);
var spanBeforeChange = affectedRange.Span;
var spanAfterChange = new TextSpan(spanBeforeChange.Start, affectedRange.NewLength);
Expand Down Expand Up @@ -291,16 +284,16 @@ private static void UnwrapCSharpSnippets(TextEdit[] razorEdits)
// This method counts the occurrences of CRLF and LF line endings in the original text. If LF line endings are more
// prevalent, it removes any CR characters from the text edits to ensure consistency with the LF style.
// This can be removed once we figure out how to generate the formatted CSharp file with the correct line endings.
private IEnumerable<TextEdit> NormalizeLineEndings(SourceText originalText, IEnumerable<TextEdit> minimalEdits)
private TextEdit[] NormalizeLineEndings(SourceText originalText, TextEdit[] edits)
{
if (originalText.HasLFLineEndings())
{
foreach (var edit in minimalEdits)
foreach (var edit in edits)
{
edit.NewText = edit.NewText.Replace("\r", "");
}
}

return minimalEdits;
return edits;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,44 +37,6 @@ public interface Bar
""");
}

[Fact]
public async Task FormatsCodeBlockDirectiveWithCRLFLineEnding()
{
await RunFormattingTestAsync(
input:
"@code {\r\n" +
" public class Foo{}\r\n" +
" public interface Bar {\r\n" +
"}\r\n" +
"}",
expected:
"@code {\r\n" +
" public class Foo { }\r\n" +
" public interface Bar\r\n" +
" {\r\n" +
" }\r\n" +
"}");
}

[Fact]
public async Task FormatsCodeBlockDirectiveWithLFLineEnding()
{
await RunFormattingTestAsync(
input:
"@code {\n" +
" public class Foo{}\n" +
" public interface Bar {\n" +
"}\n" +
"}",
expected:
"@code {\n" +
" public class Foo { }\n" +
" public interface Bar\n" +
" {\n" +
" }\n" +
"}");
}

[Fact]
public async Task FormatCSharpInsideHtmlTag()
{
Expand Down Expand Up @@ -187,64 +149,6 @@ void Method()
""");
}

[Fact]
public async Task Formats_MultipleBlocksInADirectiveWithCRLFLineEnding()
{
await RunFormattingTestAsync(
input:
"@{\r\n" +
"void Method(){\r\n" +
"var x = \"foo\";\r\n" +
"@(DateTime.Now)\r\n" +
" <p></p>\r\n" +
"var y= \"fooo\";\r\n" +
"}\r\n" +
"}\r\n" +
"<div>\r\n" +
" </div>",
expected:
"@{\r\n" +
" void Method()\r\n" +
" {\r\n" +
" var x = \"foo\";\r\n" +
" @(DateTime.Now)\r\n" +
" <p></p>\r\n" +
" var y = \"fooo\";\r\n" +
" }\r\n" +
"}\r\n" +
"<div>\r\n" +
"</div>");
}

[Fact]
public async Task Formats_MultipleBlocksInADirectiveWithLFLineEnding()
{
await RunFormattingTestAsync(
input:
"@{\n" +
"void Method(){\n" +
"var x = \"foo\";\n" +
"@(DateTime.Now)\n" +
" <p></p>\n" +
"var y= \"fooo\";\n" +
"}\n" +
"}\n" +
"<div>\n" +
" </div>",
expected:
"@{\n" +
" void Method()\n" +
" {\n" +
" var x = \"foo\";\n" +
" @(DateTime.Now)\n" +
" <p></p>\n" +
" var y = \"fooo\";\n" +
" }\n" +
"}\n" +
"<div>\n" +
"</div>");
}

[Fact]
public async Task Formats_NonCodeBlockDirectives()
{
Expand Down Expand Up @@ -1795,7 +1699,8 @@ await RunFormattingTestAsync(
private IEnumerable<int> _items = new[] { 1, 2, 3, 4, 5 };
}
""",
tagHelpers: GetComponentWithCascadingTypeParameter());
tagHelpers: GetComponentWithCascadingTypeParameter(),
skipFlipLineEndingTest: true);
}

[Fact]
Expand Down Expand Up @@ -1885,7 +1790,8 @@ await RunFormattingTestAsync(
private IEnumerable<long> _items2 = new long[] { 1, 2, 3, 4, 5 };
}
""",
tagHelpers: GetComponentWithTwoCascadingTypeParameter());
tagHelpers: GetComponentWithTwoCascadingTypeParameter(),
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Eventing.Reader;
jordi1215 marked this conversation as resolved.
Show resolved Hide resolved
using System.IO;
using System.Linq;
using System.Threading;
Expand Down Expand Up @@ -49,14 +50,29 @@ private protected async Task RunFormattingTestAsync(
ImmutableArray<TagHelperDescriptor> tagHelpers = default,
bool allowDiagnostics = false,
RazorLSPOptions? razorLSPOptions = null,
bool inGlobalNamespace = false)
bool inGlobalNamespace = false,
bool skipFlipLineEndingTest = false)
{
// Run with and without forceRuntimeCodeGeneration
await RunFormattingTestAsync(input, expected, tabSize, insertSpaces, fileKind, tagHelpers, allowDiagnostics, razorLSPOptions, inGlobalNamespace, forceRuntimeCodeGeneration: true);
await RunFormattingTestAsync(input, expected, tabSize, insertSpaces, fileKind, tagHelpers, allowDiagnostics, razorLSPOptions, inGlobalNamespace, forceRuntimeCodeGeneration: false);
await RunFormattingTestInternalAsync(input, expected, tabSize, insertSpaces, fileKind, tagHelpers, allowDiagnostics, razorLSPOptions, inGlobalNamespace, forceRuntimeCodeGeneration: true);
await RunFormattingTestInternalAsync(input, expected, tabSize, insertSpaces, fileKind, tagHelpers, allowDiagnostics, razorLSPOptions, inGlobalNamespace, forceRuntimeCodeGeneration: false);

jordi1215 marked this conversation as resolved.
Show resolved Hide resolved

// some tests are failing, skip for now, tracked by https://github.com/dotnet/razor/issues/10836
if (!skipFlipLineEndingTest)
{
// flip the line endings of the stings (LF to CRLF and vice versa) and run again
input = FlipLineEndings(input);
expected = FlipLineEndings(expected);

await RunFormattingTestInternalAsync(input, expected, tabSize, insertSpaces, fileKind, tagHelpers, allowDiagnostics, razorLSPOptions, inGlobalNamespace, forceRuntimeCodeGeneration: true);
await RunFormattingTestInternalAsync(input, expected, tabSize, insertSpaces, fileKind, tagHelpers, allowDiagnostics, razorLSPOptions, inGlobalNamespace, forceRuntimeCodeGeneration: false);
}


jordi1215 marked this conversation as resolved.
Show resolved Hide resolved
}

private async Task RunFormattingTestAsync(string input, string expected, int tabSize, bool insertSpaces, string? fileKind, ImmutableArray<TagHelperDescriptor> tagHelpers, bool allowDiagnostics, RazorLSPOptions? razorLSPOptions, bool inGlobalNamespace, bool forceRuntimeCodeGeneration)
private async Task RunFormattingTestInternalAsync(string input, string expected, int tabSize, bool insertSpaces, string? fileKind, ImmutableArray<TagHelperDescriptor> tagHelpers, bool allowDiagnostics, RazorLSPOptions? razorLSPOptions, bool inGlobalNamespace, bool forceRuntimeCodeGeneration)
{
// Arrange
fileKind ??= FileKinds.Component;
Expand Down Expand Up @@ -351,4 +367,26 @@ internal static IDocumentSnapshot CreateDocumentSnapshot(string path, ImmutableA
});
return documentSnapshot.Object;
}

private static string FlipLineEndings(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}

bool hasCRLF = input.Contains("\r\n");
bool hasLF = input.Contains("\n") && !hasCRLF;
jordi1215 marked this conversation as resolved.
Show resolved Hide resolved

if (hasCRLF)
{
return input.Replace("\r\n", "\n");
}
else if (hasLF)
{
return input.Replace("\n", "\r\n");
}

return input;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,8 @@ await RunFormattingTestAsync(
}
</GridTable>
""",
tagHelpers: tagHelpers);
tagHelpers: tagHelpers,
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836
}

[Fact]
Expand Down Expand Up @@ -595,7 +596,8 @@ await RunFormattingTestAsync(
@{
<p></p>
}
""");
""",
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836
}

[Fact]
Expand Down Expand Up @@ -1316,7 +1318,8 @@ await RunFormattingTestAsync(
public bool VarBool { get; set; }
}
""",
fileKind: FileKinds.Component);
fileKind: FileKinds.Component,
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836
}

[Fact]
Expand Down Expand Up @@ -1428,7 +1431,8 @@ await RunFormattingTestAsync(
public bool VarBool { get; set; }
}
""",
fileKind: FileKinds.Component);
fileKind: FileKinds.Component,
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836
}

[Fact]
Expand Down Expand Up @@ -1486,7 +1490,8 @@ await RunFormattingTestAsync(
public bool VarBool { get; set; }
}
""",
fileKind: FileKinds.Component);
fileKind: FileKinds.Component,
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836
}

[Fact]
Expand Down Expand Up @@ -1794,7 +1799,8 @@ await RunFormattingTestAsync(
}
</Select>
""",
tagHelpers: CreateTagHelpers());
tagHelpers: CreateTagHelpers(),
skipFlipLineEndingTest: true); // tracked by https://github.com/dotnet/razor/issues/10836

ImmutableArray<TagHelperDescriptor> CreateTagHelpers()
{
Expand Down
Loading