cd up/and/down

This commit is contained in:
Chris Wanstrath 2025-09-28 16:03:13 -07:00
parent 8544327f42
commit d3504d09f3

View File

@ -1,25 +1,42 @@
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` }