From a652b9dbc5929f9ec10e6bdd73ca84f7243f1804 Mon Sep 17 00:00:00 2001 From: Rauhul Varma Date: Tue, 10 Dec 2024 21:39:51 -0800 Subject: [PATCH] Fix comment length computation Resolved an issue where "end of line" comments matching the configured line length were incorrectly flagged as exceeding it. --- Sources/SwiftFormat/PrettyPrint/Comment.swift | 2 +- .../PrettyPrint/CommentTests.swift | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Sources/SwiftFormat/PrettyPrint/Comment.swift b/Sources/SwiftFormat/PrettyPrint/Comment.swift index 3dff9480f..43616a5b4 100644 --- a/Sources/SwiftFormat/PrettyPrint/Comment.swift +++ b/Sources/SwiftFormat/PrettyPrint/Comment.swift @@ -67,9 +67,9 @@ struct Comment { switch kind { case .line, .docLine: + self.length = text.count self.text = [text] self.text[0].removeFirst(kind.prefixLength) - self.length = self.text.reduce(0, { $0 + $1.count + kind.prefixLength + 1 }) case .block, .docBlock: var fulltext: String = text diff --git a/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift b/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift index 99b2259e2..b32342748 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/CommentTests.swift @@ -1009,6 +1009,29 @@ final class CommentTests: PrettyPrintTestCase { ) } + // Tests that "end of line" comments are flagged only when they exceed the configured line length. + func testDiagnoseMoveEndOfLineCommentAroundBoundary() { + assertPrettyPrintEqual( + input: """ + x // 789 + x // 7890 + x 1️⃣// 78901 + + """, + expected: """ + x // 789 + x // 7890 + x // 78901 + + """, + linelength: 10, + whitespaceOnly: true, + findings: [ + FindingSpec("1️⃣", message: "move end-of-line comment that exceeds the line length") + ] + ) + } + func testLineWithDocLineComment() { // none of these should be merged if/when there is comment formatting let input =