How to find the "difference" between two Paths?


#1

Part of my trouble is I don’t know the name for it, so I’ll call it a path difference. I’d like to do Path::strip_prefix with a Path that may not be a prefix, without getting an err. In other words, given paths
A = /a/b/c/d
B = /a/b/C/D
I’d like to find the path that is
B - A = …/…/C/D

To my thinking this is logically most similar to strip_prefix, but I don’t see anything like this. I understand that on Windows there is no guarantee that this operation can be done (if the two paths are on different drives), but in this case I know the two paths share a common root, so it should be safe for me even on Windows.

Any suggestions how to do this elegantly? I can’t see a solution that doesn’t involve going through Component by Component, which seems like a waste for what surely must be a common operation, in which you want to display to a user a path relative to the user’s working directory?


#2

Prior art in C++ from Boost: https://svn.boost.org/trac10/ticket/1976

This would be a great method to have, since the corner cases around symlinks are complicated to get right.


#3

This kinda reminds me of the fs::canonicalize() function to give you the relative path from the current directory to some other directory. That would probably get you halfway there.


#4

https://crates.io/crates/pathdiff?


#5

@birkenfeld, that looks exactly like what I am looking for. Thanks!