Skip to content

Commit

Permalink
fix: trim root folder / when calculating relative paths (#142)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel Roe <daniel@roe.dev>
  • Loading branch information
peterroe and danielroe committed Dec 12, 2023
1 parent 8f3d913 commit 5930a85
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { normalizeWindowsPath } from "./_internal";
const _UNC_REGEX = /^[/\\]{2}/;
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;

// Force POSIX contants
export const sep = "/";
Expand Down Expand Up @@ -211,8 +212,9 @@ export const extname: typeof path.extname = function (p) {

// relative
export const relative: typeof path.relative = function (from, to) {
const _from = resolve(from).split("/");
const _to = resolve(to).split("/");
const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");

const _fromCopy = [..._from];
for (const segment of _fromCopy) {
if (_to[0] !== segment) {
Expand Down
4 changes: 4 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ it("parse", () => {
runTest("relative", relative, [
// POSIX
["/data/orandea/test/aaa", "/data/orandea/impl/bbb", "../../impl/bbb"],
["/", "/foo/bar", "foo/bar"],
["/foo", "/", ".."],
[
() => process.cwd(),
"./dist/client/b-scroll.d.ts",
Expand All @@ -243,6 +245,8 @@ runTest("relative", relative, [

// Windows
["C:\\orandea\\test\\aaa", "C:\\orandea\\impl\\bbb", "../../impl/bbb"],
["C:\\", "C:\\foo\\bar", "foo/bar"],
["C:\\foo", "C:\\", ".."],
[
() => process.cwd().replace(/\\/g, "/"),
"./dist/client/b-scroll.d.ts",
Expand Down

0 comments on commit 5930a85

Please sign in to comment.