Skip to content

Commit

Permalink
Ensure files end with a single new line
Browse files Browse the repository at this point in the history
closes #464
  • Loading branch information
belav committed Nov 11, 2021
1 parent 5f3a317 commit aede2bb
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 9 deletions.
19 changes: 19 additions & 0 deletions Src/CSharpier.Tests/DocPrinterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,25 @@ public void Align_Should_Convert_Non_Trailing_Spaces_To_Tabs()
PrintedDocShouldBe(doc, $"+ + 1{NewLine}\t\t 2", useTabs: true);
}

[TestCase(0, "\n")]
[TestCase(0, "\r\n")]
[TestCase(1, "\r\n")]
[TestCase(1, "\r\n")]
[TestCase(2, "\r\n")]
[TestCase(2, "\r\n")]
public void Print_Should_Include_Single_NewLine(int instances, string endOfLine)
{
var doc = "1";
for (var x = 0; x < instances; x++)
{
doc += endOfLine;
}

var result = DocPrinter.DocPrinter.Print(doc, new PrinterOptions(), endOfLine);

result.Should().Be($"1{endOfLine}");
}

[Test]
public void Scratch()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,3 @@ class ClassName
AnotherAttribute
]
public class ClassName { }

2 changes: 0 additions & 2 deletions Src/CSharpier.Tests/FormattingTests/TestFiles/Comments.cst
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,3 @@ public class ClassName
// regular comment does not cause breaking
IReadOnlyList<IArgument> ICommand.Arguments => Arguments;
}


Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@ public enum E
B = A,
C = 2 + A
}

Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,3 @@ class ClassName
}
}
}

20 changes: 16 additions & 4 deletions Src/CSharpier/DocPrinter/DocPrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ public string Print()
ProcessNextCommand();
}

if (Output.Length == 0 || Output[^1] != '\n')
{
Output.Append(EndOfLine);
}
EnsureOutputEndsWithSingleNewLine();

var result = Output.ToString();
if (PrinterOptions.TrimInitialLines)
Expand All @@ -56,6 +53,21 @@ public string Print()
return result;
}

private void EnsureOutputEndsWithSingleNewLine()
{
var trimmed = 0;
for (; trimmed < Output.Length; trimmed++)
{
if (Output[^(trimmed + 1)] != '\r' && Output[^(trimmed + 1)] != '\n')
{
break;
}
}
Output.Length -= trimmed;

Output.Append(EndOfLine);
}

private void ProcessNextCommand()
{
var (indent, mode, doc) = RemainingCommands.Pop();
Expand Down

0 comments on commit aede2bb

Please sign in to comment.