|
| 1 | +import { execa } from "execa"; |
| 2 | +import chalk from "chalk"; |
| 3 | +import { stat } from "node:fs/promises"; |
| 4 | +import { resolve, join, dirname, basename } from "node:path"; |
| 5 | +import { getDefaultEditor } from "../config.js"; |
| 6 | +import { isWorktreeClean } from "../utils/git.js"; |
| 7 | +export async function newWorktreeHandler(branchName = "main", options) { |
| 8 | + try { |
| 9 | + // 1. Validate we're in a git repo |
| 10 | + await execa("git", ["rev-parse", "--is-inside-work-tree"]); |
| 11 | + console.log(chalk.blue("Checking if main worktree is clean...")); |
| 12 | + const isClean = await isWorktreeClean("."); |
| 13 | + if (!isClean) { |
| 14 | + console.warn(chalk.yellow("⚠️ Warning: Your main worktree is not clean.")); |
| 15 | + console.warn(chalk.yellow("While 'wt new' might succeed, it's generally recommended to have a clean state.")); |
| 16 | + console.warn(chalk.cyan("Run 'git status' to review changes. Consider committing or stashing.")); |
| 17 | + // Decide whether to exit or just warn. Warning might be sufficient here. |
| 18 | + // process.exit(1); |
| 19 | + } |
| 20 | + else { |
| 21 | + console.log(chalk.green("✅ Main worktree is clean.")); |
| 22 | + } |
| 23 | + // 2. Build final path for the new worktree |
| 24 | + let folderName; |
| 25 | + if (options.path) { |
| 26 | + folderName = options.path; |
| 27 | + } |
| 28 | + else { |
| 29 | + // Derive the short name for the directory from the branch name |
| 30 | + // This handles cases like 'feature/login' -> 'login' |
| 31 | + const shortBranchName = branchName.split('/').filter(part => part.length > 0).pop() || branchName; |
| 32 | + const currentDir = process.cwd(); |
| 33 | + const parentDir = dirname(currentDir); |
| 34 | + const currentDirName = basename(currentDir); |
| 35 | + // Create a sibling directory using the short branch name |
| 36 | + folderName = join(parentDir, `${currentDirName}-${shortBranchName}`); |
| 37 | + } |
| 38 | + const resolvedPath = resolve(folderName); |
| 39 | + // Check if directory already exists |
| 40 | + let directoryExists = false; |
| 41 | + try { |
| 42 | + await stat(resolvedPath); |
| 43 | + directoryExists = true; |
| 44 | + } |
| 45 | + catch (error) { |
| 46 | + // Directory doesn't exist, continue with creation |
| 47 | + } |
| 48 | + // 3. Check if branch exists |
| 49 | + const { stdout: localBranches } = await execa("git", ["branch", "--list", branchName]); |
| 50 | + const { stdout: remoteBranches } = await execa("git", ["branch", "-r", "--list", `origin/${branchName}`]); |
| 51 | + const branchExists = !!localBranches || !!remoteBranches; |
| 52 | + // 4. Create the new worktree or open the editor if it already exists |
| 53 | + if (directoryExists) { |
| 54 | + console.log(chalk.yellow(`Directory already exists at: ${resolvedPath}`)); |
| 55 | + // Check if this is a git worktree by checking for .git file/folder |
| 56 | + let isGitWorktree = false; |
| 57 | + try { |
| 58 | + await stat(join(resolvedPath, ".git")); |
| 59 | + isGitWorktree = true; |
| 60 | + } |
| 61 | + catch (error) { |
| 62 | + // Not a git worktree |
| 63 | + } |
| 64 | + if (isGitWorktree) { |
| 65 | + console.log(chalk.green(`Using existing worktree at: ${resolvedPath}`)); |
| 66 | + } |
| 67 | + else { |
| 68 | + console.log(chalk.yellow(`Warning: Directory exists but is not a git worktree.`)); |
| 69 | + } |
| 70 | + // Skip to opening editor |
| 71 | + } |
| 72 | + else { |
| 73 | + console.log(chalk.blue(`Creating new worktree for branch "${branchName}" at: ${resolvedPath}`)); |
| 74 | + if (!branchExists) { |
| 75 | + console.log(chalk.yellow(`Branch "${branchName}" doesn't exist. Creating new branch with worktree...`)); |
| 76 | + // Create a new branch and worktree in one command with -b flag |
| 77 | + await execa("git", ["worktree", "add", "-b", branchName, resolvedPath]); |
| 78 | + } |
| 79 | + else { |
| 80 | + console.log(chalk.green(`Using existing branch "${branchName}".`)); |
| 81 | + await execa("git", ["worktree", "add", resolvedPath, branchName]); |
| 82 | + } |
| 83 | + // 5. (Optional) Install dependencies if --install flag is provided |
| 84 | + if (options.install) { |
| 85 | + console.log(chalk.blue(`Installing dependencies using ${options.install} in ${resolvedPath}...`)); |
| 86 | + await execa(options.install, ["install"], { cwd: resolvedPath, stdio: "inherit" }); |
| 87 | + } |
| 88 | + } |
| 89 | + // 6. Open in the specified editor (or use configured default) |
| 90 | + const configuredEditor = getDefaultEditor(); |
| 91 | + const editorCommand = options.editor || configuredEditor; // Use option, then config, fallback is handled by config default |
| 92 | + console.log(chalk.blue(`Opening ${resolvedPath} in ${editorCommand}...`)); |
| 93 | + // Use try-catch to handle if the editor command fails |
| 94 | + try { |
| 95 | + await execa(editorCommand, [resolvedPath], { stdio: "inherit" }); |
| 96 | + } |
| 97 | + catch (editorError) { |
| 98 | + console.error(chalk.red(`Failed to open editor "${editorCommand}". Please ensure it's installed and in your PATH.`)); |
| 99 | + // Decide if you want to exit or just warn. Let's warn for now. |
| 100 | + console.warn(chalk.yellow(`Continuing without opening editor.`)); |
| 101 | + } |
| 102 | + console.log(chalk.green(`Worktree ${directoryExists ? "opened" : "created"} at ${resolvedPath}.`)); |
| 103 | + if (!directoryExists && options.install) |
| 104 | + console.log(chalk.green(`Dependencies installed using ${options.install}.`)); |
| 105 | + console.log(chalk.green(`Attempted to open in ${editorCommand}.`)); |
| 106 | + } |
| 107 | + catch (error) { |
| 108 | + if (error instanceof Error) { |
| 109 | + console.error(chalk.red("Failed to create new worktree:"), error.message); |
| 110 | + } |
| 111 | + else { |
| 112 | + console.error(chalk.red("Failed to create new worktree:"), error); |
| 113 | + } |
| 114 | + process.exit(1); |
| 115 | + } |
| 116 | +} |
0 commit comments