Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Convert path to relative

Moderators: kris

Posted: 06/12/08 11:53:54 Modified: 06/12/08 11:55:38

Unless I'm just missing it, there's no easy way currently to make a path relative to another. (FileSystem?.toRelative perhaps?) I have a home-grown solution, but I highly doubt it's efficiency. Just the same:

static import Text = tango .text .Util ;

FilePath toRelative (FilePath anchor, FilePath target) {
    char[][] split (FilePath fp) {
        Text.split(fp.folder, "/");
    }

    char[]
        resultFolders ;

    char[][]
        anchorFolders = split(anchor) ,
        targetFolders = split(target) ;

    size_t
        index = 0u ;

    for (; index < anchorFolders.length && index < targetFolders.length; ++index) {
        if (anchorFolders[index] != targetFolders[index]) {
            break;
        }
    }

    foreach (x; anchorFolders[index .. $]) {
        resultFolders ~= "../";
    }
    resultFolders ~= Text.join(targetFolders, "/");
    return new FilePath(resultFolders ~ "/" ~ target.file);
}

Chris Nicholson-Sauls

There are no responses to display.