|
| 1 | +import { existsSync } from "node:fs"; |
| 2 | +import select from "@inquirer/select"; |
| 3 | +import type { Command } from "commander"; |
| 4 | +import { error, info } from "../lib/output"; |
| 5 | +import { listWorkspaces } from "../lib/repos"; |
| 6 | +import type { ArbContext } from "../lib/types"; |
| 7 | + |
| 8 | +export function registerCdCommand(program: Command, getCtx: () => ArbContext): void { |
| 9 | + program |
| 10 | + .command("cd [name]") |
| 11 | + .summary("Navigate to a workspace directory") |
| 12 | + .description( |
| 13 | + 'Change into a workspace or worktree directory. Supports workspace/repo paths (e.g. "fix-login/frontend"). When run without arguments in a TTY, shows an interactive workspace picker.\n\nRequires shell integration (installed by install.sh) to change the shell\'s working directory. Without it, the resolved path is printed to stdout.', |
| 14 | + ) |
| 15 | + .action(async (input?: string) => { |
| 16 | + const ctx = getCtx(); |
| 17 | + |
| 18 | + if (!input) { |
| 19 | + if (!process.stdin.isTTY) { |
| 20 | + error("Usage: arb cd <workspace>"); |
| 21 | + process.exit(1); |
| 22 | + } |
| 23 | + |
| 24 | + const workspaces = listWorkspaces(ctx.baseDir); |
| 25 | + if (workspaces.length === 0) { |
| 26 | + error("No workspaces found."); |
| 27 | + process.exit(1); |
| 28 | + } |
| 29 | + |
| 30 | + const selected = await select({ |
| 31 | + message: "Select a workspace", |
| 32 | + choices: workspaces.map((name) => ({ name, value: name })), |
| 33 | + pageSize: 20, |
| 34 | + }); |
| 35 | + |
| 36 | + process.stdout.write(`${ctx.baseDir}/${selected}\n`); |
| 37 | + printHintIfNeeded(); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + const slashIdx = input.indexOf("/"); |
| 42 | + const wsName = slashIdx >= 0 ? input.slice(0, slashIdx) : input; |
| 43 | + const subpath = slashIdx >= 0 ? input.slice(slashIdx + 1) : ""; |
| 44 | + |
| 45 | + const wsDir = `${ctx.baseDir}/${wsName}`; |
| 46 | + if (!existsSync(`${wsDir}/.arbws`)) { |
| 47 | + error(`Workspace '${wsName}' does not exist`); |
| 48 | + process.exit(1); |
| 49 | + } |
| 50 | + |
| 51 | + if (subpath) { |
| 52 | + const fullPath = `${wsDir}/${subpath}`; |
| 53 | + if (!existsSync(fullPath)) { |
| 54 | + error(`'${subpath}' not found in workspace '${wsName}'`); |
| 55 | + process.exit(1); |
| 56 | + } |
| 57 | + process.stdout.write(`${fullPath}\n`); |
| 58 | + } else { |
| 59 | + process.stdout.write(`${wsDir}\n`); |
| 60 | + } |
| 61 | + |
| 62 | + printHintIfNeeded(); |
| 63 | + }); |
| 64 | +} |
| 65 | + |
| 66 | +function printHintIfNeeded(): void { |
| 67 | + if (process.stdout.isTTY && process.stderr.isTTY) { |
| 68 | + info("Hint: install shell integration to cd directly. See 'arb cd --help'."); |
| 69 | + } |
| 70 | +} |
0 commit comments