Lean 4 (Meta)programming Cookbook

Listing DirectoryπŸ”—

Contributors: Anirudh Gupta

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