Listing Directory
Listing contents of a directory
To list the contents of a directory, we use the System.FilePath.readDir method on a
System.FilePath. This returns an Array IO.FS.DirEntry containing
information about each file and subdirectory.
def listDirectory (path : System.FilePath) : IO Unit := do
let entries β path.readDir
for entry in entries do
IO.println entry.fileName
Each IO.FS.DirEntry contains the fileName (the name of the file or
directory itself) and its full path.
Recursive directory traversal
If you want to list all files in a directory tree recursively, you can use the
System.FilePath.walkDir method.
Note: You can use System.FilePath.isDir method to check if an entry is a directory.
def listAllFiles (path : System.FilePath) : IO Unit := do
let allFiles β path.walkDir
for file in allFiles do
IO.println file
Filtering during traversal
System.FilePath.walkDir takes an optional enter parameterβa function that
decides whether to recurse into a given subdirectory. This is useful for
skipping large or irrelevant folders like .git or .lake.
def listSourceFiles (path : System.FilePath) : IO Unit := do
/- Only enter directories that aren't
hidden or build artifacts -/
let filter (p : System.FilePath) : IO Bool := do
let name := p.fileName.getD ""
return name != ".git" && name != ".lake"
let files β path.walkDir (enter := filter)
for f in files do
-- Only print files with the .lean extension
if f.extension == some "lean" then
IO.println f