3

I want to check if a path is a subdirectory of another path:

use std::path::Path;

let path = Path::new("/foo/bar/");
let child = Path::new("/foo/bar/baz");

assert_eq!(is_subdirectory(path, child), true);

How to do this?

tamuhey
  • 2,904
  • 3
  • 21
  • 50

1 Answers1

6

Path's method starts_with works

use std::path::Path;

let path = Path::new("/foo/bar/");
let child = Path::new("/foo/bar/baz");

assert_eq!(child.starts_with(path), true);
assert_eq!(path.starts_with(child), false);
Alexey S. Larionov
  • 6,555
  • 1
  • 18
  • 37
  • 2
    Note: this does not work with `PathBuf::from("./a/b").starts_with(&PathBuf::from("./c/../a"))` . You have to `canonicalize` first, which [introduce its own problems](https://stackoverflow.com/questions/30511331/getting-the-absolute-path-from-a-pathbuf). – Jason Lee Jan 14 '22 at 16:28
  • @JasonLee that's kind of expected, `Path` is more like a string extension, it doesn't do computations around relative tokens `.`/`..` – Alexey S. Larionov Jan 14 '22 at 19:23