From be33ce020711917ae4a9f735145a2497124300f3 Mon Sep 17 00:00:00 2001 From: Albert Meltzer <7529386+kitbellew@users.noreply.github.com> Date: Sun, 24 Mar 2024 10:19:27 -0700 Subject: [PATCH] FormatWriter: keep braces if trailingCommas=Always --- .../scala/org/scalafmt/internal/FormatWriter.scala | 14 +++++++++----- .../trailingCommasAlwaysSingleLine.stat | 7 +------ 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala index 02589eb67c..9960320da2 100644 --- a/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala +++ b/scalafmt-core/shared/src/main/scala/org/scalafmt/internal/FormatWriter.scala @@ -5,8 +5,8 @@ import java.util.regex.Pattern import org.scalafmt.CompatCollections.JavaConverters._ import org.scalafmt.{Formatted, Scalafmt} -import org.scalafmt.config.{Comments, Docstrings, Newlines, ScalafmtConfig} -import org.scalafmt.config.{FormatEvent, RewriteScala3Settings} +import org.scalafmt.config.{Comments, Docstrings, FormatEvent, ScalafmtConfig} +import org.scalafmt.config.{Newlines, RewriteScala3Settings, TrailingCommas} import org.scalafmt.rewrite.RedundantBraces import org.scalafmt.util.TokenOps._ import org.scalafmt.util.{LiteralOps, TreeOps} @@ -156,7 +156,6 @@ class FormatWriter(formatOps: FormatOps) { while (0 <= idx) { val loc = locations(idx) val tok = loc.formatToken - val state = loc.state tok.left match { case rb: T.RightBrace => // look for "foo { bar }" val ok = tok.meta.leftOwner match { @@ -175,9 +174,14 @@ class FormatWriter(formatOps: FormatOps) { lookup.update(beg.meta.idx, tok.meta.idx -> loc.leftLineId) } case _: T.LeftBrace => + val state = loc.state + val style = loc.style lookup.remove(idx).foreach { - case (end, endOffset) if endOffset == loc.leftLineId => - val inParentheses = loc.style.spaces.inParentheses + case (end, endOffset) + if endOffset == loc.leftLineId && + (style.rewrite.trailingCommas.allowFolding || + style.getTrailingCommas != TrailingCommas.always) => + val inParentheses = style.spaces.inParentheses // remove space before "{" val prevBegState = if (0 == idx || (state.prev.split.modExt.mod ne Space)) diff --git a/scalafmt-tests/src/test/resources/trailing-commas/trailingCommasAlwaysSingleLine.stat b/scalafmt-tests/src/test/resources/trailing-commas/trailingCommasAlwaysSingleLine.stat index b5ce4b1991..0cf8d92f1d 100644 --- a/scalafmt-tests/src/test/resources/trailing-commas/trailingCommasAlwaysSingleLine.stat +++ b/scalafmt-tests/src/test/resources/trailing-commas/trailingCommasAlwaysSingleLine.stat @@ -53,9 +53,4 @@ rewrite.redundantBraces.parensForOneLineApply = true === foo { bar } >>> -Idempotency violated -=> Diff (- obtained, + expected) --foo( -- bar, --) -+foo(bar) +foo { bar }