pathrust

Given two absolute paths, how can I express one of the paths relative to the other?


I think this should be quite doable, given that there is a nice function canonicalize which normalizes paths (so I can start by normalizing my two input paths) and Path and PathBuf give us a way of iterating over the parts of paths through components. I imagine something could be worked out here to factor out a common prefix, then prepend as many .. components as remain in the anchor path to what remains of the initial input path.

My problem seems to be pretty common:

  1. How to find relative path given two absolute paths?
  2. Find a path in Windows relative to another

Solution

  • This now exists as the pathdiff crate, using the code from kennytm's answer

    You can use it as:

    extern crate pathdiff;
    
    pathdiff::diff_paths(path, base);
    

    where base is where the relative path should be applied to obtain path