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

Add end_of_line formatter #169

Merged
merged 1 commit into from
Jul 22, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
Add end_of_line formatter
  • Loading branch information
JoeRobich committed Jul 13, 2019
commit 015a43e543f5b57e31e93156fc98186f84fb03b4
1 change: 1 addition & 0 deletions src/CodeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ internal static class CodeFormatter
{
new WhitespaceFormatter(),
new FinalNewlineFormatter(),
new EndOfLineFormatter(),
}.ToImmutableArray();

public static async Task<WorkspaceFormatResult> FormatWorkspaceAsync(
Expand Down
3 changes: 2 additions & 1 deletion src/Formatters/DocumentFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public async Task<Solution> FormatAsync(
/// </summary>
protected abstract Task<SourceText> FormatFileAsync(
Document document,
SourceText sourceText,
OptionSet options,
ICodingConventionsSnapshot codingConventions,
FormatOptions formatOptions,
Expand Down Expand Up @@ -78,7 +79,7 @@ protected abstract Task<SourceText> FormatFileAsync(
logger.LogTrace(Resources.Formatting_code_file_0, Path.GetFileName(document.FilePath));

var originalSourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var formattedSourceText = await FormatFileAsync(document, options, codingConventions, formatOptions, logger, cancellationToken).ConfigureAwait(false);
var formattedSourceText = await FormatFileAsync(document, originalSourceText, options, codingConventions, formatOptions, logger, cancellationToken).ConfigureAwait(false);

return !formattedSourceText.ContentEquals(originalSourceText)
? (originalSourceText, formattedSourceText)
Expand Down
87 changes: 87 additions & 0 deletions src/Formatters/EndOfLineFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.CodingConventions;

namespace Microsoft.CodeAnalysis.Tools.Formatters
{
internal sealed class EndOfLineFormatter : DocumentFormatter
{
protected override string FormatWarningDescription => Resources.Fix_end_of_line_marker;

protected override Task<SourceText> FormatFileAsync(
Document document,
SourceText sourceText,
OptionSet options,
ICodingConventionsSnapshot codingConventions,
FormatOptions formatOptions,
ILogger logger,
CancellationToken cancellationToken)
{
return Task.Run(() =>
{
if (!TryGetEndOfLine(codingConventions, out var endOfLine))
{
return sourceText;
}

var newSourceText = sourceText;
for (var lineIndex = 0; lineIndex < newSourceText.Lines.Count; lineIndex++)
{
var line = newSourceText.Lines[lineIndex];
var lineEndingSpan = new TextSpan(line.End, line.EndIncludingLineBreak - line.End);

// Check for end of file
if (lineEndingSpan.Length == 0)
{
break;
}

var lineEnding = newSourceText.ToString(lineEndingSpan);

if (lineEnding == endOfLine)
{
continue;
}

var newLineChange = new TextChange(lineEndingSpan, endOfLine);
newSourceText = newSourceText.WithChanges(newLineChange);
}

return newSourceText;
});
}

public static bool TryGetEndOfLine(ICodingConventionsSnapshot codingConventions, out string endOfLine)
{
if (codingConventions.TryGetConventionValue("end_of_line", out string endOfLineOption))
{
endOfLine = GetEndOfLine(endOfLineOption);
return true;
}

endOfLine = null;
return false;
}

private static string GetEndOfLine(string endOfLineOption)
{
switch (endOfLineOption)
{
case "lf":
return "\n";
case "cr":
return "\r";
case "crlf":
return "\r\n";
default:
return Environment.NewLine;
}
}
}
}
25 changes: 5 additions & 20 deletions src/Formatters/FinalNewlineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ internal sealed class FinalNewlineFormatter : DocumentFormatter

protected override async Task<SourceText> FormatFileAsync(
Document document,
SourceText sourceText,
OptionSet options,
ICodingConventionsSnapshot codingConventions,
FormatOptions formatOptions,
Expand All @@ -28,13 +29,12 @@ protected override async Task<SourceText> FormatFileAsync(
return await document.GetTextAsync(cancellationToken);
}

var endOfLine = codingConventions.TryGetConventionValue("end_of_line", out string endOfLineOption)
? GetEndOfLine(endOfLineOption)
: Environment.NewLine;
if (!EndOfLineFormatter.TryGetEndOfLine(codingConventions, out var endOfLine))
{
endOfLine = Environment.NewLine;
}

var sourceText = await document.GetTextAsync(cancellationToken);
var lastLine = sourceText.Lines.Last();

var hasFinalNewline = lastLine.Span.IsEmpty;

if (insertFinalNewline && !hasFinalNewline)
Expand All @@ -60,20 +60,5 @@ protected override async Task<SourceText> FormatFileAsync(

return sourceText;
}

private string GetEndOfLine(string endOfLineOption)
{
switch (endOfLineOption)
{
case "lf":
return "\n";
case "cr":
return "\r";
case "crlf":
return "\r\n";
default:
return Environment.NewLine;
}
}
}
}
10 changes: 5 additions & 5 deletions src/Formatters/WhitespaceFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ internal sealed class WhitespaceFormatter : DocumentFormatter

protected override async Task<SourceText> FormatFileAsync(
Document document,
SourceText sourceText,
OptionSet options,
ICodingConventionsSnapshot codingConventions,
FormatOptions formatOptions,
Expand All @@ -33,7 +34,7 @@ protected override async Task<SourceText> FormatFileAsync(
}
else
{
return await GetFormattedDocumentWithDetailedChanges(document, options, cancellationToken);
return await GetFormattedDocumentWithDetailedChanges(document, sourceText, options, cancellationToken);
}
}

Expand All @@ -49,13 +50,12 @@ private static async Task<SourceText> GetFormattedDocument(Document document, Op
/// <summary>
/// Returns a formatted <see cref="SoureText"/> with multiple <see cref="TextChange"/>s for each formatting change.
/// </summary>
private static async Task<SourceText> GetFormattedDocumentWithDetailedChanges(Document document, OptionSet options, CancellationToken cancellationToken)
private static async Task<SourceText> GetFormattedDocumentWithDetailedChanges(Document document, SourceText sourceText, OptionSet options, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var originalText = await document.GetTextAsync(cancellationToken);

var formattingTextChanges = Formatter.GetFormattedTextChanges(root, document.Project.Solution.Workspace, options, cancellationToken);
return originalText.WithChanges(formattingTextChanges);

return sourceText.WithChanges(formattingTextChanges);
}
}
}
3 changes: 3 additions & 0 deletions src/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,9 @@
<data name="Add_final_newline" xml:space="preserve">
<value>Add final newline.</value>
</data>
<data name="Fix_end_of_line_marker" xml:space="preserve">
<value>Fix end of line marker.</value>
</data>
<data name="Fix_whitespace_formatting" xml:space="preserve">
<value>Fix whitespace formatting.</value>
</data>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.cs.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Nepodařilo se uložit změny formátování.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.de.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Fehler beim Speichern von Formatierungsänderungen.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.es.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Error al guardar cambios de formato.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.fr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">L'enregistrement des changements de mise en forme a échoué.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.it.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Non è stato possibile salvare le modifiche di formattazione.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.ja.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">書式変更を保存できませんでした。</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.ko.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">서식 변경 내용을 저장하지 못했습니다.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.pl.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Nie można zapisać zmian formatowania.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.pt-BR.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Falha ao salvar alterações de formatação.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.ru.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Не удалось сохранить изменения форматирования.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.tr.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">Biçimlendirme değişiklikleri kaydedilemedi.</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.zh-Hans.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">未能保存格式更改。</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
5 changes: 5 additions & 0 deletions src/xlf/Resources.zh-Hant.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@
<target state="translated">無法儲存格式化變更。</target>
<note />
</trans-unit>
<trans-unit id="Fix_end_of_line_marker">
<source>Fix end of line marker.</source>
<target state="new">Fix end of line marker.</target>
<note />
</trans-unit>
<trans-unit id="Fix_whitespace_formatting">
<source>Fix whitespace formatting.</source>
<target state="new">Fix whitespace formatting.</target>
Expand Down
4 changes: 2 additions & 2 deletions tests/Formatters/AbstractFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private string TestCode

public SolutionState TestState { get; }

private protected async Task TestAsync(string testCode, string expectedCode, ICodeFormatter formatter, IReadOnlyDictionary<string, string> editorConfig)
private protected async Task TestAsync(string testCode, string expectedCode, IReadOnlyDictionary<string, string> editorConfig)
{
TestCode = testCode;

Expand All @@ -103,7 +103,7 @@ private protected async Task TestAsync(string testCode, string expectedCode, ICo

var filesToFormat = new[] { (document, options, codingConventions) }.ToImmutableArray();

var formattedSolution = await formatter.FormatAsync(solution, filesToFormat, formatOptions, Logger, default);
var formattedSolution = await Formatter.FormatAsync(solution, filesToFormat, formatOptions, Logger, default);
var formattedDocument = formattedSolution.Projects.Single().Documents.Single();
var formattedText = await formattedDocument.GetTextAsync();

Expand Down
Loading