Skip to content

Instantly share code, notes, and snippets.

@antonioj-mattos
Forked from Slakah/Resources.scala
Created March 11, 2023 03:29
Show Gist options
  • Save antonioj-mattos/fbb83efb96e23b95f45af4741f159c40 to your computer and use it in GitHub Desktop.
Save antonioj-mattos/fbb83efb96e23b95f45af4741f159c40 to your computer and use it in GitHub Desktop.
Macro to read resources at compile time
package fastparse.protobuf
import java.nio.file.{Files, Paths}
import scala.reflect.macros.whitebox
import scala.jdk.CollectionConverters._
object Resources {
def readResource(path: String): String = macro Resources.readResourceImpl
def readResourceImpl(c: whitebox.Context)(path: c.Expr[String]): c.Expr[String] = {
import c.universe._
val Literal(Constant(thePath: String)) = path.tree
val resourcePath = Paths.get(this.getClass.getResource("/" + thePath).toURI)
val body = Files.readAllLines(resourcePath).asScala.mkString("\n")
c.Expr[String](Literal(Constant(body)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment