Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Path parts in Rust

Suppose I have the following three paths:

let file = path::Path::new("/home/meurer/test/a/01/foo.txt");
let src = path::Path::new("/home/meurer/test/a");
let dst = path::Path::new("/home/meurer/test/b");

Now, I want to copy file into dst, but for that I need to correct the paths, so that I can have new_file with a path that resolves to /home/meurer/test/b/01/foo.txt. In other words, how do I remove src from file and then append the result to dst?

/home/meurer/test/a/01/foo.txt -> /home/meurer/test/b/01/foo.txt

Note that we can't assume that src will always be this similar to dst.

like image 656
Bernardo Meurer Avatar asked Feb 04 '23 07:02

Bernardo Meurer


1 Answers

You can use Path::strip_prefix and Path::join:

use std::path::Path;

fn main() {
    let file = Path::new("/home/meurer/test/a/01/foo.txt");
    let src = Path::new("/home/meurer/test/a");
    let dst = Path::new("/home/meurer/test/b");

    let relative = file.strip_prefix(src).expect("Not a prefix");
    let result = dst.join(relative);

    assert_eq!(result, Path::new("/home/meurer/test/b/01/foo.txt"));
}

As usual, you probably don't want to use expect in your production code, it's only for terseness of the answer.

like image 108
Shepmaster Avatar answered Feb 08 '23 14:02

Shepmaster