Path.isAbs
func Path.isAbs(p: string): boolPath.isAbs reports whether p begins at a root: / on Unix; a drive and \, or \\host\share, on Windows, where \x and C:x are not absolute.
Details
- It looks only at the text: it does not touch the file system, so a path that does not exist can be absolute.
- It follows the host's convention. The examples on this page run on Unix, where an absolute path begins with
/. - On Windows a path is absolute with a drive and a root,
C:\x, or as a UNC path,\\host\share\x.\xandC:xare not, since each depends on the current drive.
Basic examples
Path.isAbs("/usr/local/bin") // true
Path.isAbs("notes.txt") // falseScope
Relative forms, with or without a leading . or .., are all relative:
Path.isAbs("src/main.ant") // false
Path.isAbs("./main.ant") // false
Path.isAbs("../lib") // false
Path.isAbs("") // falseThe root and paths that are not clean are absolute when they begin at the root:
Path.isAbs("/") // true
Path.isAbs("//srv/data") // true
Path.isAbs("/../etc") // trueA Windows path with a drive letter is relative on Unix, where C: is an ordinary name:
Path.isAbs("C:\\Users") // falseAs a function value, it filters an array of paths:
["/etc/hosts", "notes.txt", "/var/log"].filter(Path.isAbs) // ["/etc/hosts", "/var/log"]Named arguments
The parameter is named p:
Path.isAbs(p: "/home") // trueApplications
Resolve a path from a configuration file against the directory the file is in, and keep an absolute one as it is:
func resolve(dir: string, p: string): string {
if Path.isAbs(p) { p } else { Path.join([dir, p]) }
}
resolve("/etc/app", "cache") // "/etc/app/cache"
resolve("/etc/app", "/var/cache") // "/var/cache"
resolve("/etc/app", "../shared") // "/etc/shared"Reject a setting that must be absolute before using it:
func dataDir(setting: string): Result[string, Error] {
if !Path.isAbs(setting) {
return Result.fail("data dir must be absolute, got ${setting}")
}
Result.ok(Path.clean(setting))
}
println(dataDir("/srv/data/"))
println(dataDir("data"))Ok{ value: "/srv/data" }
Err{ error: Error{ message: "data dir must be absolute, got data" } }Properties and relations
Path.abs always gives an absolute path, Path.clean keeps a path absolute or relative, and Path.join is absolute when its first part is:
let paths = ["/a/b", "a/b", "./a", "../a", "/", "", "/../a"]
for p in paths {
assert(Path.isAbs(try Path.abs(p)))
assert(Path.isAbs(Path.clean(p)) == Path.isAbs(p))
assert(Path.isAbs(Path.join(["/root", p])))
}Possible issues
~ is not expanded: a path that starts with it is relative.
Path.isAbs("~/notes.txt") // falsePath.rel fails when one path is absolute and the other is not. Check both first, or make both absolute with Path.abs:
Path.rel("/srv", "data").isOk() // falseSee also
Path.abs · Path.clean · Path.join · Path.rel · Path
