Skip to content

Commit

Permalink
Formatted: define Try[_]/Throwable ctors
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Jul 8, 2024
1 parent cfed1f8 commit 888030c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
12 changes: 12 additions & 0 deletions scalafmt-core/shared/src/main/scala/org/scalafmt/Formatted.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package org.scalafmt

import org.scalafmt.config.ScalafmtConfig

import scala.util.Try

sealed abstract class Formatted {

def toEither: Either[Throwable, String] = this match {
Expand All @@ -19,11 +21,21 @@ object Formatted {
case class Success(formattedCode: String) extends Formatted
case class Failure(e: Throwable) extends Formatted

def apply(formatted: Try[String]): Formatted = formatted
.fold(Failure.apply, Success.apply)

private[scalafmt] case class Result(
formatted: Formatted,
config: ScalafmtConfig,
) {
def get: String = formatted.get
}

private[scalafmt] object Result {
def apply(res: Try[String], config: ScalafmtConfig): Result =
Result(Formatted(res), config)
def apply(res: Throwable, config: ScalafmtConfig): Result =
Result(Failure(res), config)
}

}
16 changes: 7 additions & 9 deletions scalafmt-core/shared/src/main/scala/org/scalafmt/Scalafmt.scala
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ object Scalafmt {
if (filename == defaultFilename) Success(baseStyle)
else baseStyle.getConfigFor(filename).map(getStyleByFile)
styleTry.fold(
x => Formatted.Result(Formatted.Failure(x), baseStyle),
Formatted.Result(_, baseStyle),
formatCodeWithStyle(code, _, range, filename),
)
}
Expand Down Expand Up @@ -105,15 +105,13 @@ object Scalafmt {
val (prefix, unixCode) = splitCodePrefix(
if (isWin) code.replaceAll(WinLineEnding, UnixLineEnding) else code,
)
doFormat(unixCode, style, filename, range) match {
case Failure(e) => Formatted.Result(Formatted.Failure(e), style)
case Success(x) =>
val s = if (prefix.isEmpty && x.isEmpty) UnixLineEnding else prefix + x
val asWin = style.lineEndings == LineEndings.windows ||
(isWin && style.lineEndings == LineEndings.preserve)
val res = if (asWin) s.replaceAll(UnixLineEnding, WinLineEnding) else s
Formatted.Result(Formatted.Success(res), style)
val res = doFormat(unixCode, style, filename, range).map { x =>
val s = if (prefix.isEmpty && x.isEmpty) UnixLineEnding else prefix + x
val asWin = style.lineEndings == LineEndings.windows ||
(isWin && style.lineEndings == LineEndings.preserve)
if (asWin) s.replaceAll(UnixLineEnding, WinLineEnding) else s
}
Formatted.Result(res, style)
}

private def doFormat(
Expand Down

0 comments on commit 888030c

Please sign in to comment.