The Scala Toolkit

How to read a directory?

Language

You can require the entire toolkit in a single line:

//> using toolkit latest

Alternatively, you can require just a specific version of OS-Lib:

//> using dep com.lihaoyi::os-lib:0.9.1

In your build.sbt, you can add a dependency on the toolkit:

lazy val example = project.in(file("."))
  .settings(
    scalaVersion := "3.3.4",
    libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
  )

Alternatively, you can require just a specific version of OS-Lib:

libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.9.1"

In your build.sc file, you can add a dependency on the Toolkit:

object example extends ScalaModule {
  def scalaVersion = "3.3.4"
  def ivyDeps =
    Agg(
      ivy"org.scala-lang::toolkit:0.1.7"
    )
}

Alternatively, you can require just a specific version of OS-Lib:

ivy"com.lihaoyi::os-lib:0.9.1"

Paths

A fundamental data type in OS-Lib is os.Path, representing a path on the filesystem. An os.Path is always an absolute path.

OS-Lib also provides os.RelPath (relative paths) and os.SubPath (a relative path which cannot ascend to parent directories).

Typical starting points for making paths are os.pwd (the current working directory), os.home (the current user’s home directory), os.root (the root of the filesystem), or os.temp.dir() (a new temporary directory).

Paths have a / method for adding path segments. For example:

val etc: os.Path = os.root / "etc"

Reading a directory

os.list returns the contents of a directory:

val entries: Seq[os.Path] = os.list(os.root / "etc")

Or if we only want subdirectories:

val dirs: Seq[os.Path] = os.list(os.root / "etc").filter(os.isDir)

To recursively descend an entire subtree, change os.list to os.walk. To process results on the fly rather than reading them all into memory first, substitute os.walk.stream.

Contributors to this page: