summaryrefslogtreecommitdiff
path: root/examples/scala-js/sbt-plugin/src/main/scala/scala/scalajs/sbtplugin/env/VirtualFileMaterializer.scala
blob: fca1c478b9efb75a42d064cfe0f9c333836f9d8b (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package scala.scalajs.sbtplugin.env

import scala.scalajs.tools.io.{IO => _, _}

import sbt.IO

import java.io.File

/** A helper class to temporarily store virtual files to the filesystem.
 *  
 *  Can be used with tools that require real files.
 *  @param singleDir if true, forces files to be copied into
 *      [[cacheDir]]. Useful to setup include directories for
 *      example.
 */
final class VirtualFileMaterializer(singleDir: Boolean = false) {

  val cacheDir = {
    val dir = IO.createTemporaryDirectory
    dir.deleteOnExit()
    dir
  }

  /** Create a target file to write/copy to. Will also call
   *  deleteOnExit on the file.
   */
  private def trgFile(name: String): File = {
    val f = new File(cacheDir, name)
    f.deleteOnExit()
    f
  }

  private def materializeFileVF(vf: FileVirtualFile): File = {
    if (!singleDir) vf.file
    else {
      val trg = trgFile(vf.name)
      IO.copyFile(vf.file, trg)
      trg
    }
  }

  def materialize(vf: VirtualTextFile): File = vf match {
    case vf: FileVirtualFile => materializeFileVF(vf)
    case _ =>
      val trg = trgFile(vf.name)
      IO.write(trg, vf.content)
      trg
  }

  def materialize(vf: VirtualBinaryFile): File = vf match {
    case vf: FileVirtualFile => materializeFileVF(vf)
    case _ =>
      val trg = trgFile(vf.name)
      IO.write(trg, vf.content)
      trg
  }

  /** Removes the cache directory. Any operation on this
   *  VirtualFileMaterializer is invalid after [[close]] has been
   *  called.
   */
  def close(): Unit = {
    cacheDir.listFiles().foreach(_.delete)
    cacheDir.delete()
  }

}