Function std.path.asRelativePath
Transforms path into a path relative to base.
auto asRelativePath(CaseSensitive cs = CaseSensitive .osDefault, R1, R2)
(
R1 path,
R2 base
)
if ((isNarrowString!R1 || isRandomAccessRange!R1 && hasSlicing!R1 && isSomeChar!(ElementType!R1) && !isConvertibleToString!R1) && (isNarrowString!R2 || isRandomAccessRange!R2 && hasSlicing!R2 && isSomeChar!(ElementType!R2) && !isConvertibleToString!R2));
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:
- 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.
Parameters
| Name | Description |
|---|---|
| path | path to transform |
| base | absolute path |
| cs | whether filespec comparisons are sensitive or not; defaults to
CaseSensitive |
Returns
a random access range of the transformed path
See Also
Example
import std .array;
version (Posix)
{
writeln(asRelativePath("foo", "/bar") .array); // "foo"
writeln(asRelativePath("/foo/bar", "/foo/bar") .array); // "."
writeln(asRelativePath("/foo/bar", "/foo/baz") .array); // "../bar"
writeln(asRelativePath("/foo/bar/baz", "/foo/woo/wee") .array); // "../../bar/baz"
writeln(asRelativePath("/foo/bar/baz", "/foo/bar") .array); // "baz"
}
else version (Windows)
{
writeln(asRelativePath("foo", `c:\bar`) .array); // "foo"
writeln(asRelativePath(`c:\foo\bar`, `c:\foo\bar`) .array); // "."
writeln(asRelativePath(`c:\foo\bar`, `c:\foo\baz`) .array); // `..\bar`
writeln(asRelativePath(`c:\foo\bar\baz`, `c:\foo\woo\wee`) .array); // `..\..\bar\baz`
writeln(asRelativePath(`c:/foo/bar/baz`, `c:\foo\woo\wee`) .array); // `..\..\bar\baz`
writeln(asRelativePath(`c:\foo\bar\baz`, `c:\foo\bar`) .array); // "baz"
writeln(asRelativePath(`c:\foo\bar`, `d:\foo`) .array); // `c:\foo\bar`
writeln(asRelativePath(`\\foo\bar`, `c:\foo`) .array); // `\\foo\bar`
}
else
static assert(0);
Authors
Lars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Kühne, Andrei Alexandrescu