diff --git a/src/pwd.mjs b/src/pwd.mjs index baec72b..17cc68a 100644 --- a/src/pwd.mjs +++ b/src/pwd.mjs @@ -82,5 +82,7 @@ export function locate(cwd = process.cwd()) { // Collapse $HOME to `~` for tidy display. export function tilde(p, home) { - return home && p.startsWith(home) ? "~" + p.slice(home.length) : p; + if (!home || p === home) return home ? "~" : p; + const relative = p.slice(home.length); + return p.startsWith(home) && relative.startsWith(path.sep) ? "~" + relative : p; } diff --git a/test/pwd.test.mjs b/test/pwd.test.mjs new file mode 100644 index 0000000..65806db --- /dev/null +++ b/test/pwd.test.mjs @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import path from "node:path"; +import test from "node:test"; + +import { tilde } from "../src/pwd.mjs"; + +test("tilde shortens the home directory itself", () => { + const home = path.join("C:", "Users", "mosh"); + + assert.equal(tilde(home, home), "~"); +}); + +test("tilde shortens paths inside home", () => { + const home = path.join("C:", "Users", "mosh"); + const project = path.join(home, "repo"); + + assert.equal(tilde(project, home), `~${path.sep}repo`); +}); + +test("tilde does not shorten sibling paths with the same prefix", () => { + const home = path.join("C:", "Users", "mosh"); + const sibling = path.join("C:", "Users", "mosh-other", "repo"); + + assert.equal(tilde(sibling, home), sibling); +});