sandlot/src/commands/close.ts

36 lines
1.2 KiB
TypeScript

import { join } from "path"
import { homedir } from "os"
import { basename } from "path"
import { unlink } from "fs/promises"
import * as git from "../git.ts"
import * as vm from "../vm.ts"
import * as state from "../state.ts"
import { die } from "../fmt.ts"
export async function action(branch: string, opts: { force?: boolean } = {}) {
const root = await git.repoRoot()
const session = await state.getSession(root, branch)
const worktreeAbs = session?.worktree ?? join(homedir(), '.sandlot', basename(root), branch)
if (!opts.force && session && await git.isDirty(worktreeAbs)) {
die(`Branch "${branch}" has unsaved changes. Run "sandlot save ${branch}" first, or use -f to force.`)
}
await vm.clearActivity(worktreeAbs, branch)
await git.removeWorktree(worktreeAbs, root)
.catch((e) => console.warn(`⚠ Failed to remove worktree: ${e.message}`))
await unlink(join(root, '.sandlot', branch))
.catch(() => {}) // symlink may not exist
await git.deleteLocalBranch(branch, root)
.catch((e) => console.warn(`⚠ Failed to delete branch ${branch}: ${e.message}`))
if (session) {
await state.removeSession(root, branch)
}
console.log(`✔ Closed session ${branch}`)
}