Skip to content

Commit

Permalink
ScalafmtReflect: improve parseConfigWith error
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Apr 27, 2022
1 parent e18b40b commit 210e610
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ object ScalafmtDynamicError {
class ConfigMissingVersion(configPath: Path)
extends ConfigError(configPath, "Missing version")

class ConfigParseError(configPath: Path, why: String)
extends ConfigError(configPath, s"Invalid config: $why")
class ConfigParseError(configPath: Path, why: String, cause: Throwable = null)
extends ConfigError(configPath, s"Invalid config: $why", cause)

class CannotDownload(
configPath: Path,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.scalafmt.dynamic

import com.typesafe.config.ConfigFactory
import java.io.Closeable
import java.net.URLClassLoader
import java.nio.file.Path
import org.scalafmt.dynamic.exceptions._
import org.scalafmt.dynamic.utils.ReflectUtils._
Expand Down Expand Up @@ -57,19 +58,36 @@ case class ScalafmtReflect(
}

private def parseConfigWith(
f: => Try[Object]
)(g: Throwable => Throwable): Try[ScalafmtReflectConfig] =
f: => Try[Object],
path: Path = null
): Try[ScalafmtReflectConfig] = {
@inline def fail(msg: String, e: Throwable) =
Failure(new ScalafmtDynamicError.ConfigParseError(path, msg, e))
f.map { configured =>
new ScalafmtReflectConfig(this)(configured.invoke("get"))
}.recoverWith { case ReflectionException(e) => Failure(g(e)) }
}.recoverWith {
case e: ReflectiveOperationException =>
val msg = classLoader match {
case x: URLClassLoader =>
ScalafmtDynamicError.getCorruptedClassPath(version, x.getURLs)
case _ => "Config dynamic load error"
}
fail(msg, e)
case e => fail(e.getMessage, e.getCause)
}
}

def parseConfig(path: Path): Try[ScalafmtReflectConfig] =
parseConfigWith(parseConfigPost300(path)) { e =>
new ScalafmtDynamicError.ConfigParseError(path, e.getMessage)
}
parseConfigWith(parseConfigPost300(path), path)

def parseConfigFromString(
path: Path,
text: String
): Try[ScalafmtReflectConfig] =
parseConfigWith(parseConfigPre300(text), path)

def parseConfigFromString(text: String): Try[ScalafmtReflectConfig] =
parseConfigWith(parseConfigPre300(text))(identity)
parseConfigWith(parseConfigPre300(text))

private def parseConfigPost300(path: Path): Try[Object] = {
if (version < ScalafmtVersion(3, 0, 0, 7)) parseConfigPre300(path)
Expand Down

0 comments on commit 210e610

Please # to comment.