https://kotlinlang.org logo
e

eric.kolotyluk

02/02/2016, 1:35 AM
Copy code
case class TraversablePaths(roots: Path*)
  (traverseDirectoriesDown: Boolean = false, traverseDirectoriesUp: Boolean = false, traverseFiles: Boolean = true, traverseLinks: Boolean = true, traverseFailures: Boolean = false)
  extends Traversable[Path] {
  
  // TODO - the sense of preVisit and postVisit does not make sense...
  
  /** Concrete foreach implementation.
    *  
    * foreach is the basic method of traversing Scala collections,
    * enabling Traversable to support composable monadic operations
    * such as filter, fold, map, etc.
    * 
    * java.nio.Files.walkFileTree does most of the heavy lifting,
    * but we try to make it more Scala friendly.
    * 
    * See also [[<http://www.scala-lang.org/api/current/index.html#scala.collection.Traversable>]]
    */
  override def foreach[U](f: Path => U) {
    class visitor extends SimpleFileVisitor[Path] {
      override def preVisitDirectory(path: Path, attrs: BasicFileAttributes) : FileVisitResult = {
        if (traverseDirectoriesDown) f(path)
        CONTINUE
      }
      override def postVisitDirectory(path: Path, e: IOException) : FileVisitResult = {
        if (traverseDirectoriesUp) f(path)
        CONTINUE
      }
      override def visitFile(path: Path, attrs: BasicFileAttributes) : FileVisitResult = {
        if (traverseFiles) f(path)
        CONTINUE
      }
      override def visitFileFailed(path: Path, e: IOException) : FileVisitResult = {
        if (traverseFailures) f(path)
        CONTINUE
      }
    }
    
    // Walk a tree of infinite depth, following symbolic links if requested.
    // NIO keeps track of symbolic links so that cycles are not
    // followed indefinitely.
    if (traverseLinks)
      roots.foreach(walkFileTree(_, EnumSet.of(FOLLOW_LINKS), Integer.MAX_VALUE, new visitor))
    else
     roots.foreach(walkFileTree(_, new visitor))
  }

}