You will use
pooka/file:list_directory,create_directories,remove_directorypooka/path:path.join,path.extension,path.stem
The whole program
module main
import pooka/file.{FileError}
import pooka/io
import pooka/list
import pooka/path
import pooka/string
/// Every file in `folder` with the given extension, sorted by name.
files_with(folder: String, wanted: String) -> Result(List(String), FileError) {
let names = file.list_directory(folder)?
Ok(
names
|> list.filter(fn(name: String) { path.extension(name) == Some(wanted) })
|> list.sort_by(string.compare)
)
}
main() {
// A small shelf to look at.
let _ = file.create_directories("shelf")
loop name in ["moon.txt", "owl.txt", "lamp.png", "attic.txt"] {
let _ = file.write(path.join(["shelf", name]), "")
}
match files_with("shelf", ".txt") {
Ok(names) -> list.each(names, fn(name: String) {
io.println(path.stem(name))
Nil
})
Error(problem) -> {
io.eprintln(problem.message)
Nil
}
}
loop name in ["moon.txt", "owl.txt", "lamp.png", "attic.txt"] {
let _ = file.delete(path.join(["shelf", name]))
}
let _ = file.remove_directory("shelf")
}
Run it
The program makes a small shelf folder, lists it, and removes it again:
$ pooka run
attic
moon
owl
How it works
- Names, not paths.
file.list_directory("shelf")returns the names inside the folder, like"owl.txt", in no particular order. Usepath.jointo turn a name back into a path. - Extensions keep their dot.
path.extension("owl.txt")isSome(".txt"), and a name without one givesNone. Comparing withSome(wanted)handles both. - Sort before showing.
list.sort_by(string.compare)puts the names in alphabetical order, andpath.stemdrops the extension for display. - One
?, oneResult.files_withreturnsResult(List(String), FileError), so a missing folder is a message, not a crash.
Try next: use file.is_directory to walk into subfolders, calling your function again for each one.