diff --git a/src/utils/index.ts b/src/utils/index.ts index 85cc989..7cf3b28 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -10,3 +10,4 @@ export type { LineMatchMode } from "./match-line"; export { compileLineMatcher } from "./match-line"; export { isProcessGroupAlive, killProcessGroup } from "./process-group"; export { walkCommands, wordToString } from "./shell-utils"; +export { shortenPath } from "./shorten-path"; diff --git a/src/utils/shorten-path.test.ts b/src/utils/shorten-path.test.ts new file mode 100644 index 0000000..d49aaba --- /dev/null +++ b/src/utils/shorten-path.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; + +import { shortenPath } from "./shorten-path"; + +describe("shortenPath", () => { + it("shortens the home directory and its descendants", () => { + expect(shortenPath("/home/dev", "/home/dev")).toBe("~"); + expect(shortenPath("/home/dev/project", "/home/dev")).toBe("~/project"); + }); + + it("does not shorten sibling paths sharing the home prefix", () => { + expect(shortenPath("/home/developer/project", "/home/dev")).toBe( + "/home/developer/project", + ); + }); +}); diff --git a/src/utils/shorten-path.ts b/src/utils/shorten-path.ts new file mode 100644 index 0000000..3d577cd --- /dev/null +++ b/src/utils/shorten-path.ts @@ -0,0 +1,11 @@ +import { homedir } from "node:os"; +import { sep } from "node:path"; + +/** Replace a home-directory prefix with `~` for display. */ +export function shortenPath(path: string, home = homedir()): string { + if (path === home) return "~"; + if (path.startsWith(`${home}${sep}`)) { + return `~${path.slice(home.length)}`; + } + return path; +}