The OpenD Programming Language

asRelativePath

Transforms path into a path relative to base.

The returned path is relative to base, which is usually the current working directory. base must be an absolute path, and it is always assumed to refer to a directory. If path and base refer to the same directory, the function returns '.'.

The following algorithm is used:

  1. If path is a relative directory, return it unaltered.
  2. Find a common root between path and base. If there is no common root, return path unaltered.
  3. Prepare a string with as many ../ or ..\ as necessary to reach the common root from base path.
  4. Append the remaining segments of path to the string and return.

In the second step, path components are compared using filenameCmp!cs, where cs is an optional template parameter determining whether the comparison is case sensitive or not. See the filenameCmp documentation for details.

Parameters

path R1

path to transform

base R2

absolute path

cs

whether filespec comparisons are sensitive or not; defaults to CaseSensitive.osDefault

Return Value

Type: auto

a random access range of the transformed path

Examples

import std.array;
version (Posix)
{
    assert(asRelativePath("foo", "/bar").array == "foo");
    assert(asRelativePath("/foo/bar", "/foo/bar").array == ".");
    assert(asRelativePath("/foo/bar", "/foo/baz").array == "../bar");
    assert(asRelativePath("/foo/bar/baz", "/foo/woo/wee").array == "../../bar/baz");
    assert(asRelativePath("/foo/bar/baz", "/foo/bar").array == "baz");
}
else version (Windows)
{
    assert(asRelativePath("foo", `c:\bar`).array == "foo");
    assert(asRelativePath(`c:\foo\bar`, `c:\foo\bar`).array == ".");
    assert(asRelativePath(`c:\foo\bar`, `c:\foo\baz`).array == `..\bar`);
    assert(asRelativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`).array == `..\..\bar\baz`);
    assert(asRelativePath(`c:/foo/bar/baz`, `c:\foo\woo\wee`).array == `..\..\bar\baz`);
    assert(asRelativePath(`c:\foo\bar\baz`, `c:\foo\bar`).array == "baz");
    assert(asRelativePath(`c:\foo\bar`, `d:\foo`).array == `c:\foo\bar`);
    assert(asRelativePath(`\\foo\bar`, `c:\foo`).array == `\\foo\bar`);
}
else
    static assert(0);

See Also

Meta