How to find the "difference" between two Paths?

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?

Prior art in C++ from Boost:

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

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.

1 Like

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