The OpenD Programming Language

relativePath

Translates path into a relative path.

The returned path is relative to base, which is by default taken to be the current working directory. If specified, 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.

This function allocates memory.

string
relativePath
(
string path
,
lazy string base = getcwd()
)

Parameters

cs

Whether matching path name components against the base path should be case-sensitive or not.

path string

A path name.

base string

The base path to construct the relative path from.

Return Value

Type: string

The relative path.

Throws

Exception if the specified base directory is not absolute.

Examples

assert(relativePath("foo") == "foo");

version (Posix)
{
    assert(relativePath("foo", "/bar") == "foo");
    assert(relativePath("/foo/bar", "/foo/bar") == ".");
    assert(relativePath("/foo/bar", "/foo/baz") == "../bar");
    assert(relativePath("/foo/bar/baz", "/foo/woo/wee") == "../../bar/baz");
    assert(relativePath("/foo/bar/baz", "/foo/bar") == "baz");
}
version (Windows)
{
    assert(relativePath("foo", `c:\bar`) == "foo");
    assert(relativePath(`c:\foo\bar`, `c:\foo\bar`) == ".");
    assert(relativePath(`c:\foo\bar`, `c:\foo\baz`) == `..\bar`);
    assert(relativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`) == `..\..\bar\baz`);
    assert(relativePath(`c:\foo\bar\baz`, `c:\foo\bar`) == "baz");
    assert(relativePath(`c:\foo\bar`, `d:\foo`) == `c:\foo\bar`);
}

See Also

asRelativePath which does not allocate memory

Meta