Skip to content

PathBuf set_file_name and with_file_name need docs for input abspaths #50116

Open
@pnkfelix

Description

@pnkfelix

Looking at:

https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.with_file_name

and

https://doc.rust-lang.org/std/path/struct.PathBuf.html#method.set_file_name

I had thought, based on what was written there, that the code would extract the filename alone from the input, dropping the directory prefix.

But apparently what will actually happen is that it drops all the content from self and just turns it into a copy of the input.

(And if you give it a relative path with multiple components, then it effectively pushes all of the components onto self)

I don't actually mind the current behavior, and it is easy enough to workaround myself. (Basically, I think set_file_name and with_file_name are somewhat misleadingly misnamed...) But we should document it it, perhaps with concrete examples.

Here is an example of what I am getting at (playpen):

fn main() {
    use std::path::Path;

    println!("EXAMPLE 1");
    let path1 = Path::new("/dir1/file1.txt");
    let path2 = Path::new("/dir2/file2.txt");
    println!("path1: {}", path1.display());
    println!("path2: {}", path2.display());
    println!("path1.with_file_name(path2): {}", path1.with_file_name(path2).display());
    println!("Felix expected /dir1/file2.txt");
    
    println!("");
    println!("EXAMPLE 2");
    let path1 = Path::new("dir1/file1.txt");
    let path2 = Path::new("dir2/file2.txt");
    println!("path1: {}", path1.display());
    println!("path2: {}", path2.display());
    println!("path1.with_file_name(path2): {}", path1.with_file_name(path2).display());
    println!("Felix expected dir1/file2.txt");
}

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.T-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