File.walk
func File.walk(dir: string): Result[Array[string], Error]File.walk returns every file below dir, at any depth, as paths relative to dir. It lists files and not directories, follows a link at dir but no link below it, and returns the paths in lexical order, the order in which strings compare.
Details
- The paths are relative to
dir, not to the working directory. Join each withdirto reach the file:Path.join([dir, path]). - Hidden files, whose names begin with a dot, are listed, and so are the files inside hidden directories.
- An empty directory leaves no trace in the result.
- A symbolic link below
diris listed as a file and never descended into, whatever it points at. - A
dirthat is missing or not a directory isErr, and so is a directory below it that cannot be read.
The examples on this page run in a directory that holds these files:
proj/.env
proj/README.md
proj/docs/guide.md
proj/src/main.ant
proj/src/util/strings.ant
proj/src/util/strings_test.ant
proj/.git/configBasic examples
List every file below a directory, at any depth:
println(File.walk("proj/src"))Ok{ value: ["main.ant", "util/strings.ant", "util/strings_test.ant"] }Unwrap the paths with try and loop over them. In a script, try ends the script on an Err:
for path in try File.walk("proj") {
println(path)
}.env
.git/config
README.md
docs/guide.md
src/main.ant
src/util/strings.ant
src/util/strings_test.antScope
A directory with no files below it gives an empty array, even when it holds empty directories:
try File.mkdir("blank/a/b")
println(File.walk("blank"))Ok{ value: [] }The order is lexical element by element, so the files of a come before those of a-b, although - sorts before / as a code point:
let paths = try File.walk("order")
println(paths)
println(paths.sort())["a/x", "a-b/x"]
["a-b/x", "a/x"]Names are compared code point by code point: uppercase before lowercase, 10 before 9:
println(try File.walk("mixed"))["10.txt", "9.txt", "Zeta.txt", "apple.txt"]dir may be spelled with ./, .., or a final /; the paths below it come out the same:
println(try File.walk("./proj/../proj/docs/"))["guide.md"]Call it in a pipe, with the directory first:
let count = "proj" | File.walk() | Result.map({ x.length() })
println(count)Ok{ value: 7 }Applications
Find the test files of a project:
let tests = try File.walk("proj")
| Array.filter({ x.endsWith("_test.ant") })
println(tests)["src/util/strings_test.ant"]Count the files of each extension:
let byExt = (try File.walk("proj")).groupBy(Path.ext)
for entry in byExt.entries() {
let ext = if entry.key.isEmpty() { "(none)" } else { entry.key }
println("${ext}: ${entry.value.length()}")
}.env: 1
(none): 1
.md: 2
.ant: 3Add up the size of a tree. Join each path with dir to stat it, and wrap a failure with the path:
func treeSize(dir: string): Result[int, Error] {
var total = 0
for path in try File.walk(dir) {
let full = Path.join([dir, path])
let info = try (File.stat(full) | Result.wrapErr("size of ${full}"))
total += info.size
}
Result.ok(total)
}
println(treeSize("proj/docs"))
println(treeSize("proj/src"))Ok{ value: 21 }
Ok{ value: 134 }Find the Markdown pages that do not mention a word. Path.match skips hidden names at any depth, and a page that cannot be read ends the script:
let dir = "proj"
let missing: Array[string] = []
for path in try File.walk(dir) {
if !Path.match("**/*.md", path).unwrapOr(false) {
continue
}
let text = try File.read(Path.join([dir, path]))
if !text.contains("Start") {
missing.push(path)
}
}
println(missing)["README.md"]Properties and relations
No path is absolute, and each one joined with dir names an entry that exists. File.stat with follow: false checks the entry itself, so a dangling link counts too:
let dir = "proj"
let paths = try File.walk(dir)
assert(paths.every({ !Path.isAbs(x) }))
assert(paths.every({ File.stat(Path.join([dir, x]), follow: false).isOk() }))For a pattern that matches only files, File.glob gives File.walk filtered with Path.match, in the same order:
let pattern = "**/*.ant"
let walked = (try File.walk("proj")).filter({ Path.match(pattern, x).unwrapOr(false) })
assert(walked == (try File.glob(pattern, dir: "proj")))File.list names the entries of one directory; File.walk replaces each subdirectory with the files inside it:
println(try File.list("proj/src"))
println(try File.walk("proj/src"))["main.ant", "util"]
["main.ant", "util/strings.ant", "util/strings_test.ant"]For a descent of your own, one that needs the directories too or skips some, File.readDir gives each entry of a directory with its kind.
Possible issues
The paths are relative to dir. Reading one as it comes back looks for it in the working directory instead:
let paths = try File.walk("proj/docs")
println(File.read(paths[0]))
println(File.read(Path.join(["proj/docs", paths[0]])))Err{ error: Error{ message: "open guide.md: no such file or directory" } }
Ok{ value: "# Guide\n\nStart here.\n" }A missing dir and a file in place of a directory are errors, not an empty array:
println(File.walk("nothing"))
println(File.walk("proj/README.md"))Err{ error: Error{ message: "stat nothing: no such file or directory" } }
Err{ error: Error{ message: "proj/README.md is not a directory" } }Copying a tree file by file with File.walk loses its empty directories, since they are not listed:
try File.mkdir("site/assets")
try File.write("site/index.html", "<h1>Hi</h1>")
for path in try File.walk("site") {
let to = Path.join(["copy", path])
try File.mkdir(Path.dir(to))
try File.copy(Path.join(["site", path]), to)
}
println(File.exists("copy/assets"))falseFile.copyAll copies the whole tree, empty directories included.
A symbolic link is listed as a file, even when it points at a directory, and the files behind it are not listed. A dangling link is listed too:
try File.symlink("src", "proj/linked")
try File.symlink("nowhere", "proj/dangling")
let paths = try File.walk("proj")
println(paths.filter({ !x.contains("/") }))
println(File.stat("proj/linked").map({ x.isDir }))
println(File.exists("proj/dangling"))[".env", "README.md", "dangling", "linked"]
Ok{ value: true }
falseFile.readDir reports such an entry with isSymlink true and isDir false, so a listing of your own can tell links from files.
See also
File.list · File.readDir · File.glob · File.stat · File.copyAll · Path.join · Path.match
