Is there an ideal way and/or crate for handling user input of paths?


I’ve been working on a CLI bashdoc. I’ve tried to improve the error handling of invalid paths but I was wondering if there was some way or crate that does a really good job of handling file paths or fuzzy finding or something else?



The standard library has a great Path module with tons of useful functions for manipulating paths.


It seems like canonicalize is what I was looking for.


canonicalize will normalize paths to remove intermediate . components, and collapses foo/bar/.. to just foo/. It won’t actually handle “invalid paths” in every sense. And it definitely doesn’t do fuzzy matching.

One suggestion I have is updating your interfaces to accept AsRef<Path> generics instead of &str. e.g. here:

This will allow you to continue passing &str and the argument gets coerced into a Path. You should also return Result type, since a lot of path-handling code will be fallible. If you need to normalize the path, then it’s just a matter of putting something like this at the top of the function:

let p = p.as_ref().canonicalize()?;

Also, Path and PathBuf both implement is_dir() so you don’t need to pass a separate bool.

The final suggestion I might throw out there is that you might find the walkdir crate useful!