Skip to content

Windows: success of canonicalizing r"\" depends on whether set_current_dir has been called #49342

@vitiral

Description

@vitiral

Problem: sometimes `Path::new(r"").canonicalize() fails

Note: apparently this isn't necessarily against the spec (a better link to the windows spec would be nice)

In Windows it's relative to what drive your current working directory is at the time. If your current directory is in the C drive then C:\ would be the root. If the current directory is the D drive then D:\ would be the root. There is no absolute root.

Regardless of whether it is against the spec or not, I think basing the "root location" off of the current_dir is a best practice. At the very least, having canonicalize(r"\") fail is unexpected.

Full Report

I hit this problem during one of my tests for path_abs. The way I handle it is thorny (and there is still a TODO hidden in there).

The below test passes on windows (and linux obviously):

    if cfg!(windows) {
        let result = Path::new(r"\").canonicalize();
        assert!(result.is_ok(), "Should work before set_current_dir is called: {:?}", result);
    }
    let tmp = tempdir::TempDir::new("ex").unwrap();
    let tmp = tmp.path();
    let tmp_abs = PathArc::new(&tmp).canonicalize().unwrap();
    env::set_current_dir(&tmp_abs).unwrap();
    if cfg!(windows) {
        let result = Path::new(r"\").canonicalize();
        assert!(result.is_err());
        println!("Got ERR cananonicalizing root: {}", result.unwrap_err());
    }\

The way I handle this in path_abs is the following:

  • If the first component is Root
  • Get the current_dir and use it's root instead.

That code is here (it's messy and tied to resolving the absolute path in general).

Rust Info

Running in Windows Appveyor: https://ci.appveyor.com/project/vitiral/path-abs

  stable installed - rustc 1.24.1 (d3ae9a9e0 2018-02-27)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ioArea: `std::io`, `std::fs`, `std::net` and `std::path`C-enhancementCategory: An issue proposing an enhancement or a PR with one.O-windowsOperating system: WindowsT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions