Skip to content

Commit

Permalink
In IOLifts.fromOption, build the exception string at compile time, no…
Browse files Browse the repository at this point in the history
…t runtime (#15)

Co-authored-by: Oscar Boykin <oboykin@netflix.com>
  • Loading branch information
johnynek and Oscar Boykin authored Jan 6, 2023
1 parent 161652c commit bf7bc3d
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions src/main/scala/afenton/bazel/bsp/IOLifts.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package afenton.bazel.bsp

import cats.effect.IO
import scala.quoted.*
import java.nio.file.Paths
import scala.util.control.NonFatal

object IOLifts {
/** Convert an Option to an IO or make a good error message
Expand All @@ -18,19 +20,17 @@ object IOLifts {

def fromOptionImpl[A: Type, B: Type](expr: Expr[Option[A]], fn: Expr[A => IO[B]])(using ctx: Quotes): Expr[IO[B]] = {
val rootPosition = ctx.reflect.Position.ofMacroExpansion
val file = Expr(rootPosition.sourceFile.path)
val line = Expr((rootPosition.startLine + 1).toString)
val show = Expr(expr.show)
val absFile: String = rootPosition.sourceFile.path
val file = try {
Paths.get("").toAbsolutePath.relativize(Paths.get(absFile)).toString
} catch {
case NonFatal(_) => absFile
}
val line = rootPosition.startLine + 1
val msg = Expr(s"expected ${expr.show} to be defined in file: $file at line: $line")

val errorCase = '{
val str = new StringBuilder
str.append("expected ")
str.append(${show})
str.append(" to be defined in file: ")
str.append(${file})
str.append(" at line: ")
str.append(${line})
IO.raiseError[B](new java.util.NoSuchElementException(str.toString()))
IO.raiseError[B](new java.util.NoSuchElementException($msg))
}

expr match {
Expand Down

0 comments on commit bf7bc3d

Please sign in to comment.