Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions packages/filesystem/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import { joinPath } from "./utils";

describe("joinPath", () => {
it("joins relative path segments as an absolute normalized path", () => {
expect(joinPath("path1", "path2")).toBe("/path1/path2");
});

it("does not create duplicate slashes when segments already contain slashes", () => {
expect(joinPath("/path1", "/path2")).toBe("/path1/path2");
expect(joinPath("/path1/", "/path2/")).toBe("/path1/path2");
expect(joinPath("path1/", "path2/")).toBe("/path1/path2");
expect(joinPath("/path1/", "path2")).toBe("/path1/path2");
});

it("keeps root-relative behavior when the first segment is empty", () => {
expect(joinPath("", "file.txt")).toBe("/file.txt");
expect(joinPath("", "dir", "file.txt")).toBe("/dir/file.txt");
});

it("handles root path segments", () => {
expect(joinPath("/", "file.txt")).toBe("/file.txt");
expect(joinPath("/", "dir", "file.txt")).toBe("/dir/file.txt");
});

it("skips empty path segments", () => {
expect(joinPath("dir", "", "file.txt")).toBe("/dir/file.txt");
expect(joinPath("", "dir", "", "file.txt", "")).toBe("/dir/file.txt");
});

it("returns empty string when no meaningful path is provided", () => {
expect(joinPath()).toBe("");
expect(joinPath("")).toBe("");
expect(joinPath("", "")).toBe("");
expect(joinPath("/")).toBe("");
expect(joinPath("/", "")).toBe("");
});

it("normalizes multiple adjacent slashes inside segments", () => {
expect(joinPath("//path1//", "//path2//")).toBe("/path1/path2");
expect(joinPath("path1//nested", "path2")).toBe("/path1/nested/path2");
});
});
29 changes: 19 additions & 10 deletions packages/filesystem/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
export function joinPath(...paths: string[]): string {
let path = "";
for (let value of paths) {
if (!value) {
let result = "";

for (const path of paths) {
if (!path) {
continue;
}
if (!value.startsWith("/")) {
value = `/${value}`;

let start = 0;

for (let i = 0; i <= path.length; i++) {
if (i !== path.length && path[i] !== "/") {
continue;
}

if (i > start) {
result += `/${path.slice(start, i)}`;
}

start = i + 1;
}
if (value.endsWith("/")) {
value = value.substring(0, value.length - 1);
}
path += value;
}
return path;

return result;
}
Loading