Path.abs
func Path.abs(p: string): Result[string, Error]Path.abs returns p as an absolute path, resolved against the working directory and cleaned, so "" gives the working directory. It is Err only when Os.cwd would be.
Details
- The working directory is the one
antwas started in, asOs.cwdreports it, not the directory of the script. Path.absworks on the text: the path does not have to exist, and symbolic links are not resolved; useFile.realPathfor the path with every link resolved.- The result is clean, and so is an absolute
p:Path.abs("/a/./b/../c/")isOk("/a/c").Path.abs("")is the working directory. - It is
Erronly whenOs.cwdwould be.
Basic examples
A relative path becomes the working directory joined with it:
let cwd = try Os.cwd()
let notes = try Path.abs("notes.txt")
println(try Path.rel(cwd, notes))
println(Path.isAbs(notes))notes.txt
trueA clean absolute path comes back unchanged:
Path.abs("/etc/hosts") // Ok{ value: "/etc/hosts" }Scope
Nothing needs to be at the path. A file that does not exist yet has an absolute path too:
let report = try Path.abs("out/report.html")
println(File.exists(report))
println(report.endsWith("/out/report.html"))false
trueApplications
Show where a run writes its files, relative to the working directory when it is below it:
func describe(p: string): Result[string, Error] {
let cwd = try Os.cwd()
let full = try Path.abs(p)
let rel = try Path.rel(cwd, full)
let outside = rel == ".." || rel.startsWith("../")
Result.ok(if outside { full } else { "./${rel}" })
}
println(try describe("build/app.js"))
println(try describe("/var/log/app.log"))./build/app.js
/var/log/app.logPass a child process an absolute path, so that it means the same file in the child's own dir:
try File.mkdir("work")
let input = try Path.abs("data/input.txt")
let text = try Cmd.read(Cmd.new("cat", args: [input], dir: "work"))
println(text)helloProperties and relations
The result is absolute, and Path.abs of a clean absolute path is that path:
let full = try Path.abs("src/main.ant")
assert(Path.isAbs(full))
assert(try Path.abs("/srv/app/main.ant") == "/srv/app/main.ant")Path.rel from the working directory leads back to the relative path:
let cwd = try Os.cwd()
let full = try Path.abs("src/main.ant")
assert(try Path.rel(cwd, full) == "src/main.ant")Possible issues
~ is not the home directory. Path.abs takes it as a directory named ~ inside the working directory. $NAME is not expanded either; both are ordinary names:
let wrong = try Path.abs("~/notes.txt")
println(wrong.endsWith("/~/notes.txt"))
let right = Path.join([try Os.home(), "notes.txt"])
println(Path.isAbs(right))true
trueSee also
Path.isAbs · Path.rel · Path.join · Path.clean · Os.cwd · File.realPath
