|
| 1 | +package com.passivsystems.embed |
| 2 | + |
| 3 | +package object Embed { |
| 4 | + import scala.language.experimental.macros |
| 5 | + |
| 6 | + /** Embeds file content directly into source at compile time. |
| 7 | + * |
| 8 | + * The content file is a path relative to the source file. |
| 9 | + */ |
| 10 | + def embed (path: String): String = macro Embed.embed |
| 11 | + |
| 12 | + /** Embeds file content and string interpolates it at compile time. |
| 13 | + * |
| 14 | + * The content file is a path relative to the source file. |
| 15 | + * |
| 16 | + * Note: the curly braces are required, and only simple identifier expressions are supported. |
| 17 | + * e.g. {{{ ${myVal} }}} |
| 18 | + * |
| 19 | + * {{{ |
| 20 | + * val divId = "uniqueId" |
| 21 | + * val html = sEmbed("status.html") |
| 22 | + * }}} |
| 23 | + * Where status.html (in same directory): |
| 24 | + * {{{ |
| 25 | + * <div id="${divId}">Div content</div> |
| 26 | + * }}} |
| 27 | + */ |
| 28 | + def sEmbed(path: String): String = macro Embed.sEmbed |
| 29 | + |
| 30 | + private[this] object Embed { |
| 31 | + import scala.reflect.macros.blackbox.Context |
| 32 | + |
| 33 | + def embed(c: Context)(path: c.Expr[String]): c.Expr[String] = { |
| 34 | + import c.universe._ |
| 35 | + embedImpl(c)(path, false) |
| 36 | + } |
| 37 | + |
| 38 | + def sEmbed(c: Context)(path: c.Expr[String]): c.Expr[String] = { |
| 39 | + import c.universe._ |
| 40 | + embedImpl(c)(path, true) |
| 41 | + } |
| 42 | + |
| 43 | + def embedImpl(c: Context)(path: c.Expr[String], interpolate: Boolean): c.Expr[String] = { |
| 44 | + import c.universe._ |
| 45 | + |
| 46 | + val q"${pathConst: String}" = path.tree |
| 47 | + |
| 48 | + val pos = path.tree.pos |
| 49 | + val currentDirectory = pos.source.file.file.getAbsoluteFile.getParentFile |
| 50 | + val rawContent = contentOf(currentDirectory, pathConst) |
| 51 | + |
| 52 | + if (interpolate) interpolateExpr(c)(rawContent) |
| 53 | + else constantExpr(c)(rawContent) |
| 54 | + } |
| 55 | + |
| 56 | + def contentOf(currentDirectory: java.io.File, path: String) = { |
| 57 | + val source = scala.io.Source.fromFile(new java.io.File(currentDirectory, path)) |
| 58 | + val content = source.mkString |
| 59 | + source.close() |
| 60 | + content |
| 61 | + } |
| 62 | + |
| 63 | + def interpolateExpr(c: Context)(content: String): c.Expr[String] = { |
| 64 | + import c.universe._ |
| 65 | + val parts = content.split("\\$\\{([^\\}]*)\\}").toSeq |
| 66 | + val args = "\\$\\{([^\\}]*)\\}".r.findAllMatchIn(content).map(_.group(1)).map(c.parse(_)).toSeq |
| 67 | + c.Expr[String](q"scala.StringContext(..$parts).s(..$args)") |
| 68 | + } |
| 69 | + |
| 70 | + def constantExpr(c: Context)(content: String): c.Expr[String] = { |
| 71 | + import c.universe._ |
| 72 | + c.Expr[String](q"$content") |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments