Skip to content

Commit c730a75

Browse files
authored
Merge pull request swiftlang#236 from dabelknap/trailing-lines
Prevent extra trailing newlines in a file.
2 parents 877d4fb + 7a9360b commit c730a75

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

+16
Original file line numberDiff line numberDiff line change
@@ -1598,7 +1598,23 @@ private final class TokenStreamCreator: SyntaxVisitor {
15981598
var isStartOfFile = token.previousToken == nil
15991599
let trivia = token.leadingTrivia
16001600

1601+
// If we're at the end of the file, determine at which index to stop checking trivia pieces to
1602+
// prevent trailing newlines.
1603+
var cutoffIndex: Int? = nil
1604+
if token.tokenKind == TokenKind.eof {
1605+
cutoffIndex = 0
1606+
for (index, piece) in trivia.enumerated() {
1607+
switch piece {
1608+
case .newlines(_), .carriageReturns(_), .carriageReturnLineFeeds(_):
1609+
continue
1610+
default:
1611+
cutoffIndex = index + 1
1612+
}
1613+
}
1614+
}
1615+
16011616
for (index, piece) in trivia.enumerated() {
1617+
if let cutoff = cutoffIndex, index == cutoff { break }
16021618
switch piece {
16031619
case .lineComment(let text):
16041620
if index > 0 || isStartOfFile {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
public class NewlineTests: PrettyPrintTestCase {
2+
public func testLeadingNewlines() {
3+
let input =
4+
"""
5+
6+
7+
let a = 123
8+
"""
9+
10+
let expected =
11+
"""
12+
let a = 123
13+
14+
"""
15+
16+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
17+
}
18+
19+
public func testLeadingNewlinesWithComments() {
20+
let input =
21+
"""
22+
23+
24+
// Comment
25+
26+
let a = 123
27+
"""
28+
29+
let expected =
30+
"""
31+
// Comment
32+
33+
let a = 123
34+
35+
"""
36+
37+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
38+
}
39+
40+
public func testTrailingNewlines() {
41+
let input =
42+
"""
43+
let a = 123
44+
45+
46+
"""
47+
48+
let expected =
49+
"""
50+
let a = 123
51+
52+
"""
53+
54+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
55+
}
56+
57+
public func testTrailingNewlinesWithComments() {
58+
let input =
59+
"""
60+
let a = 123
61+
62+
// Comment
63+
64+
65+
"""
66+
67+
let expected =
68+
"""
69+
let a = 123
70+
71+
// Comment
72+
73+
"""
74+
75+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
76+
}
77+
}

0 commit comments

Comments
 (0)