scala/ScalaBook/chapter-10/src/main/scala/scalabook/file/MemFS.scala

package scalabook.file

import scala.collection.mutable
import path.Path

class MemFS(val name: String) extends VFS[MemFile] {
  private[this] val MemRoot: MemFile =
    new MemoryFolder(this, Path.UnixPath("/"))

  protected[file] val cache =
    mutable.HashMap[Path, MemFile](MemRoot.path -> MemRoot)

  def mkpath(path: String) = Path.UnixPath("/" + path)

  override def root = MemRoot
  
  def roots = MemRoot :: Nil

  def container = None

  def newTempFile(prefix: String, suffix: String) =
    throw new UnsupportedOperationException

  override def newFolder(path: Path) =
    cache.get(path) match {
      case Some(vfile) =>
        if(vfile.isFolder) vfile else error(path + " is a file")
      case None => {
        val vfile = new MemoryFolder(this, path)
        cache(path) = vfile
        vfile
      }
    }

  override def newFile(path: Path) =
    cache.get(path) match {
      case Some(vfile) =>
        if(vfile.isFile) vfile else error(path + " is a folder")
      case None => {
        val vfile = new MemoryFile(this, path)
        cache(path) = vfile
        vfile
      }
    }

  def resolve(path: Path) = cache.get(path)

  override def toString = "MemFS(" + name + ")"
}