I am trying to get the absolute path of PathBuf object, but I found that PathBuf doesn't have a related implement seemingly.
So I attempted to achieve it by myself,
I assume for now that the relative path here is relative to the folder path of the current caller:
use anyhow::Result;
use std::env;
use std::path::PathBuf;
fn absolute(path: PathBuf) -> Result<PathBuf> {
let current_dir = env::current_dir()?;
Ok(current_dir.join(path))
}
fn main() {
let path = PathBuf::from("dir");
let abs_path = absolute(path);
println!("{:?}", abs_path);
}
Output:
Ok("D:\\dev\\rustic\\del_later\\dir")
It seems to be running as I expected.
Unfortunately, when I changed the input path to:
...
fn main() {
let path = PathBuf::from("../dir");
...
}
What I got:
Ok("D:\\dev\\rustic\\del_later\\../dir")
Looks terrible. I expect to get this instead of that:
// :>
Ok("D:\\dev\\rustic\\dir")
I searched for solutions and found a popular one is using std::fs::canonicalize:
use anyhow::Result;
use std::fs;
use std::path::PathBuf;
fn absolute(path: PathBuf) -> Result<PathBuf> {
let abs_path = fs::canonicalize(path)?;
Ok(abs_path)
}
fn main() {
let path = PathBuf::from("../lagerange");
let abs_path = absolute(path);
println!("{:?}", abs_path);
}
Output:
Ok("\\\\?\\D:\\dev\\rustic\\lagerange")
It looks almost as expected, except for the strange part "\\\\?\\"
Actually, I noticed a topic in this community that mentioned it before, probably is Rust's unique terminology or something else. I will go over it carefully later, but that's not the point.
The point is that std::fs::canonicalize cannot handle non-existent paths.
But I don't care if the input path exists, I just need to get its absolute path.
I'd be better grateful if anyone is willing to give me an idea to achieve that.