Skip to content

Instantly share code, notes, and snippets.

@fthomas
Created July 11, 2014 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fthomas/45c4df6a8272352b854d to your computer and use it in GitHub Desktop.
Save fthomas/45c4df6a8272352b854d to your computer and use it in GitHub Desktop.
List contents of a directory with scalaz-stream
package scalaz.stream
import java.nio.file.{DirectoryStream, Path}
import java.nio.file.Files._
import scalaz.concurrent.Task
import Process._
object os {
def listDirectory(dir: Path): Process[Task, Path] =
evalIterable(newDirectoryStream(dir))
def listDirectoryDeep(dir: Path, followSymlinks: Boolean = false): Process[Task, Path] =
listDirectory(dir).flatMap { path =>
emit(path) ++ {
val recur = isDirectory(path) && (!isSymbolicLink(path) || followSymlinks)
if (recur) listDirectoryDeep(path, followSymlinks) else halt
}
}
private type CloseableIterable[A] =
java.lang.Iterable[A] with java.io.Closeable
private def evalIterable[A](iterable: => CloseableIterable[A]): Process[Task, A] =
io.resource(Task.delay(iterable))(r => Task.delay(r.close())) { r =>
lazy val it = r.iterator()
Task.delay { if (it.hasNext) it.next() else throw End }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment