diff --git a/app/nose/bin/cd.ts b/app/nose/bin/cd.ts index 60d3704..3f2c937 100644 --- a/app/nose/bin/cd.ts +++ b/app/nose/bin/cd.ts @@ -1,26 +1,43 @@ -import { join, dirname } from "path" -import { readdirSync } from "fs" +import { dirname, resolve, isAbsolute } from "path" +import { statSync } from "fs" import { projectDir } from "@/project" import { getState, setState } from "@/session" -export default async function (path: string) { - if (path.endsWith("/")) path = path.slice(0, path.length - 1) - const cwd = getState("cwd") - const root = cwd || projectDir() +export default async function (path?: string) { + const root = projectDir() + const cwd = getState("cwd") || root - if (path == "..") { - if (root === projectDir()) return - - setState("cwd", dirname(cwd)) + if (!path || path.trim() === "") { + setState("cwd", root) return } - for (const file of readdirSync(root, { withFileTypes: true })) { - if (file.name === path && file.isDirectory()) { - setState("cwd", join(root, file.name)) + if (path.endsWith("/")) path = path.slice(0, -1) + + if (path === ".") return + if (path === "..") { + if (cwd !== root) { + const parent = dirname(cwd) + if (parent.startsWith(root)) { + setState("cwd", parent) + } + } + return + } + + const target = isAbsolute(path) ? resolve(path) : resolve(cwd, path) + + if (!target.startsWith(root)) + return "" + + try { + const stat = statSync(target) + if (stat.isDirectory()) { + setState("cwd", target) return } + } catch { } return { error: `${path} doesn't exist` } -} \ No newline at end of file +}