Skip to content

Commit 3f7dad6

Browse files
authored
Respect home path boundaries in pwd (#13)
1 parent e1fd805 commit 3f7dad6

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

src/pwd.mjs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,5 +82,7 @@ export function locate(cwd = process.cwd()) {
8282

8383
// Collapse $HOME to `~` for tidy display.
8484
export function tilde(p, home) {
85-
return home && p.startsWith(home) ? "~" + p.slice(home.length) : p;
85+
if (!home || p === home) return home ? "~" : p;
86+
const relative = p.slice(home.length);
87+
return p.startsWith(home) && relative.startsWith(path.sep) ? "~" + relative : p;
8688
}

test/pwd.test.mjs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import assert from "node:assert/strict";
2+
import path from "node:path";
3+
import test from "node:test";
4+
5+
import { tilde } from "../src/pwd.mjs";
6+
7+
test("tilde shortens the home directory itself", () => {
8+
const home = path.join("C:", "Users", "mosh");
9+
10+
assert.equal(tilde(home, home), "~");
11+
});
12+
13+
test("tilde shortens paths inside home", () => {
14+
const home = path.join("C:", "Users", "mosh");
15+
const project = path.join(home, "repo");
16+
17+
assert.equal(tilde(project, home), `~${path.sep}repo`);
18+
});
19+
20+
test("tilde does not shorten sibling paths with the same prefix", () => {
21+
const home = path.join("C:", "Users", "mosh");
22+
const sibling = path.join("C:", "Users", "mosh-other", "repo");
23+
24+
assert.equal(tilde(sibling, home), sibling);
25+
});

0 commit comments

Comments
 (0)