Path
Path holds pure functions over paths in the host's convention: / on Unix, \ and drive letters on Windows. They work on the text and never touch the file system, except Path.abs.
Details
- Every function works on the text alone: the path does not have to exist, and nothing on disk is read or changed. Path.abs also reads the working directory. File touches the file system.
- The examples on this page use
/. - Path.join and Path.clean give a cleaned path, and the empty path is
"."for both. Path.match does not cleanpath.
Basic examples
Build a path from parts with Path.join:
Path.join(["src", "lib", "main.ant"]) // "src/lib/main.ant"
Path.join(["a", "b/../c", "d.ant"]) // "a/c/d.ant"Take a path apart with Path.dir, Path.base, and Path.ext:
let p = "src/lib/main.ant"
Path.dir(p) // "src/lib"
Path.base(p) // "main.ant"
Path.ext(p) // ".ant"Ask how one path leads to another with Path.rel, and whether a path matches a glob pattern with Path.match:
Path.rel("/srv/app", "/srv/app/lib/db.ant") // Ok{ value: "lib/db.ant" }
Path.match("**/*.ant", "src/main.ant") // Ok{ value: true }Scope
Path.clean gives the shortest equivalent path, and Path.isAbs tells an absolute path from a relative one:
Path.clean("a//b/./c/..") // "a/b"
Path.clean("") // "."
Path.isAbs("/etc/hosts") // true
Path.isAbs("etc/hosts") // falseNo parts, or only empty ones, join to ".":
Path.join([]) // "."
Path.join(["", ""]) // "."A wildcard does not match a name that begins with ., unless hidden: true is given:
Path.match("*", ".env") // Ok{ value: false }
Path.match("*", ".env", hidden: true) // Ok{ value: true }**/*.ant also matches a file at the top, and src/** matches everything below src but not src itself. Wildcards compare code points exactly, so case counts:
Path.match("**/*.ant", "a.ant") // Ok{ value: true }
Path.match("src/**", "src") // Ok{ value: false }
Path.match("*.TXT", "a.txt") // Ok{ value: false }A malformed pattern is Err, not false:
Path.match("[a-", "x") // Err{ error: Error{ message: "malformed pattern [a-: [ without ]" } }Path.rel climbs out of base with .. when it has to. It is Err when no relative path leads from base to target: when one is absolute and the other is not, or when base climbs out with .. further than target does:
Path.rel("src/lib", "src/test/a.ant") // Ok{ value: "../test/a.ant" }
Path.rel("/srv", "app") // Err{ error: Error{ message: "no relative path leads from /srv to app" } }
Path.rel("../a", "b") // Err{ error: Error{ message: "no relative path leads from ../a to b" } }Path.abs resolves a relative path against the working directory. It still looks only at the text: the path does not have to exist, and links stay as written (File.realPath resolves them):
let cwd = try Os.cwd()
let notes = try Path.abs("notes.txt")
println(Path.isAbs(notes))
println(notes == Path.join([cwd, "notes.txt"]))true
trueFunctions by job
Building and cleaning
- Path.join: join parts with the separator, cleaned
- Path.clean: the shortest equivalent path
Taking a path apart
- Path.dir: all but the last element
- Path.base: the last element
- Path.ext: the extension of the last element
Absolute and relative
- Path.isAbs: whether a path is absolute
- Path.abs: a path made absolute against the working directory
- Path.rel: a target as a path from a base
Matching
- Path.match: whether a path matches a glob pattern, the syntax File.glob takes
Applications
Put each source file's output beside the others in one directory, with a new extension:
func outputPath(src: string, outDir: string): string {
let name = Path.base(src)
Path.join([outDir, "${name.trimSuffix(Path.ext(name))}.html"])
}
for src in ["docs/index.md", "docs/guide/intro.md"] {
println(outputPath(src, "site"))
}site/index.html
site/intro.htmlTo keep each source file's directory under the output directory, use Path.rel. This script takes the source and output directories, then the source files. It rejects a source whose relative path starts with ..:
func firstElement(rel: string): string {
var head = rel
while Path.dir(head) != "." {
head = Path.dir(head)
}
head
}
func outputPath(source: string, src: string, out: string): Result[string, Error] {
let rel = try Path.rel(src, source)
if firstElement(rel) == ".." {
return Result.fail("${source} is outside ${src}")
}
let name = Path.base(rel).trimSuffix(Path.ext(rel))
Result.ok(Path.join([out, Path.dir(rel), name + ".html"]))
}
let args = Os.args()
if args.length() < 2 {
return Result.fail("usage: paths <src> <out> <file>...")
}
let src = args[0]
let out = args[1]
for source in args.slice(2, args.length()) {
println("${source} -> ${try outputPath(source, src, out)}")
}content/index.md -> public/index.html
content//blog/first.post.md -> public/blog/first.post.html
./content/about/team.md -> public/about/team.htmlPick the test files out of a tree. File.walk gives paths relative to the directory, so Path.join puts the directory back in front:
try File.mkdir("project/src/util")
try File.write("project/src/main.ant", "")
try File.write("project/src/main_test.ant", "")
try File.write("project/src/util/strings_test.ant", "")
for path in try File.walk("project") {
if try Path.match("**/*_test.ant", path) {
println(Path.join(["project", path]))
}
}project/src/main_test.ant
project/src/util/strings_test.antShow a path relative to a project root:
let root = try Path.abs("project")
let file = Path.join([root, "src", "main.ant"])
println(try Path.rel(root, file))src/main.antProperties and relations
A clean path is its directory joined with its base, joining cleans, and joining a base with a path relative to it gives the path back:
let p = "src/lib/main.ant"
assert(Path.join([Path.dir(p), Path.base(p)]) == p)
assert(Path.join(["a//b", "./c"]) == Path.clean("a//b/./c"))
assert(Path.join([Path.dir(p), try Path.rel(Path.dir(p), p)]) == p)Possible issues
A part that starts with a separator does not start over at the root. Path.join keeps every part:
Path.join(["/srv", "/etc/passwd"]) // "/srv/etc/passwd"Path.abs does not check that the path exists or resolve links; File.realPath does, so it is Err for a path that leads nowhere:
try File.write("notes.txt", "")
println(File.realPath("notes.txt").isOk())
println(Path.abs("missing.txt").isOk())
println(File.realPath("missing.txt").isOk())true
true
falsePath.match does not clean path, so a leading ./ keeps a pattern from matching. Clean the path first:
Path.match("*.txt", "./a.txt") // Ok{ value: false }
Path.match("*.txt", Path.clean("./a.txt")) // Ok{ value: true }See also
File · File.glob · File.walk · File.realPath · Os.cwd · Os.home · Walk a directory and match globs
