summaryrefslogtreecommitdiff
path: root/examples/scala-js/tools/shared/src/main/scala/scala/scalajs/tools/io/CacheUtils.scala
blob: 14773f8230e808c492abe1ad1e8e6db879b387b8 (plain) (blame)
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
45
46
47
48
49
50
51
52
package scala.scalajs.tools.io

object CacheUtils {

  def joinVersions(vs: Option[String]*): Option[String] = {
    val bld = new StringBuilder

    @scala.annotation.tailrec
    def loop(vs: Seq[Option[String]]): Option[String] = {
      vs match {
        case Some(v) :: vss =>
          bld.append(mangleVersionString(v))
          loop(vss)
        case None :: _ =>
          None
        case Nil =>
          Some(bld.toString)
      }
    }

    loop(vs.toList)
  }

  def joinVersions(vs: String*): String =
    vs.map(mangleVersionString _).mkString

  private def mangleVersionString(str: String) = s"${str.length}:$str"

  def cached(version: Option[String], output: VirtualFile,
      cache: Option[WritableVirtualTextFile])(action: => Unit): Unit = {

    val upToDate = output.exists && (
        for {
          v <- version
          c <- cache if c.exists
        } yield c.content == v
    ).getOrElse(false)

    // Are we outdated?
    if (!upToDate) {
      action

      // Write cache
      for (c <- cache; v <- version) {
        val w = c.contentWriter
        try w.write(v)
        finally w.close()
      }
    }
  }

}