Function std.path.relativePath
Translates path into a relative path.
string relativePath(CaseSensitive cs = CaseSensitive .osDefault)
(
string path,
lazy string base = getcwd()
);
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:
- If
pathis a relative directory, return it unaltered. - Find a common root between
pathandbase. If there is no common root, returnpathunaltered. - Prepare a string with as many
or../as necessary to reach the common root from base path...\ - Append the remaining segments of
pathto 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.
Parameters
| Name | Description |
|---|---|
| cs | Whether matching path name components against the base path should be case-sensitive or not. |
| path | A path name. |
| base | The base path to construct the relative path from. |
Returns
The relative path.
See Also
asRelativePath which does not allocate memory
Throws
Exception if the specified base directory is not absolute.
Example
writeln(relativePath("foo")); // "foo"
version (Posix)
{
writeln(relativePath("foo", "/bar")); // "foo"
writeln(relativePath("/foo/bar", "/foo/bar")); // "."
writeln(relativePath("/foo/bar", "/foo/baz")); // "../bar"
writeln(relativePath("/foo/bar/baz", "/foo/woo/wee")); // "../../bar/baz"
writeln(relativePath("/foo/bar/baz", "/foo/bar")); // "baz"
}
version (Windows)
{
writeln(relativePath("foo", `c:\bar`)); // "foo"
writeln(relativePath(`c:\foo\bar`, `c:\foo\bar`)); // "."
writeln(relativePath(`c:\foo\bar`, `c:\foo\baz`)); // `..\bar`
writeln(relativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`)); // `..\..\bar\baz`
writeln(relativePath(`c:\foo\bar\baz`, `c:\foo\bar`)); // "baz"
writeln(relativePath(`c:\foo\bar`, `d:\foo`)); // `c:\foo\bar`
}
Authors
Lars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Kühne, Andrei Alexandrescu