sandlot/src/commands/edit.ts

36 lines
889 B
TypeScript

import { resolve } from "path"
import { existsSync } from "fs"
import { die } from "../fmt.ts"
import { requireSession } from "./helpers.ts"
export async function action(branch: string, file: string) {
const editor = process.env.EDITOR
if (!editor) {
die("$EDITOR is not set.")
}
const { session } = await requireSession(branch)
const worktree = resolve(session.worktree)
const path = resolve(worktree, file)
if (!path.startsWith(worktree + "/") && path !== worktree) {
die("File path escapes the worktree.")
}
if (!existsSync(path)) {
die(`File not found: ${file}`)
}
const [cmd, ...args] = editor.split(/\s+/)
const proc = Bun.spawn([cmd, ...args, path], {
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
})
const exitCode = await proc.exited
if (exitCode !== 0) {
die(`Editor exited with code ${exitCode}.`)
}
}