forked from scala/scala3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConstantHolderGenerator.scala
44 lines (33 loc) · 1022 Bytes
/
ConstantHolderGenerator.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import scala.annotation.tailrec
import sbt._
import org.scalajs.ir.ScalaJSVersions
object ConstantHolderGenerator {
/** Generate a *.scala file that contains the given values as literals. */
def generate(dir: File, fqn: String, values: (String, Any)*): Seq[File] = {
val (fullPkg@(_ :+ pkg)) :+ objectName = fqn.split('.').toSeq
val out = dir / (objectName + ".scala")
val defs = for {
(name, value) <- values
} yield {
s"val $name = ${literal(value)}"
}
val scalaCode =
s"""
package ${fullPkg.mkString(".")}
private[$pkg] object $objectName {
${defs.mkString("\n")}
}
"""
IO.write(out, scalaCode)
Seq(out)
}
@tailrec
private final def literal(v: Any): String = v match {
case s: String => "raw\"\"\"" + s + "\"\"\""
case b: Boolean => b.toString
case f: File => literal(f.getAbsolutePath)
case _ =>
throw new IllegalArgumentException(
"Unsupported value type: " + v.getClass)
}
}