Skip to main content

git_worktree_manager/operations/
worktree.rs

1/// Core worktree lifecycle operations.
2///
3use std::path::{Path, PathBuf};
4
5use console::style;
6
7use crate::constants::{
8    default_worktree_path, format_config_key, CONFIG_KEY_BASE_BRANCH, CONFIG_KEY_BASE_PATH,
9    CONFIG_KEY_INTENDED_BRANCH,
10};
11use crate::error::{CwError, Result};
12use crate::git;
13use crate::shared_files;
14
15use super::ai_tools::LaunchOptions;
16use crate::cli::EmitFormat;
17use crate::messages;
18
19/// Create a new worktree with a feature branch.
20pub fn create_worktree(
21    branch_name: &str,
22    base_branch: Option<&str>,
23    path: Option<&str>,
24    initial_prompt: Option<&str>,
25    launch_opts: &LaunchOptions<'_>,
26    emit: EmitFormat,
27) -> Result<PathBuf> {
28    let repo = git::get_repo_root(None)?;
29
30    // Validate branch name
31    if !git::is_valid_branch_name(branch_name, Some(&repo)) {
32        let error_msg = git::get_branch_name_error(branch_name);
33        return Err(CwError::InvalidBranch(messages::invalid_branch_name(
34            &error_msg,
35        )));
36    }
37
38    // In json emit mode, route human-readable output to stderr so stdout
39    // stays clean for the single-line JSON result.
40    macro_rules! say {
41        ($($arg:tt)*) => {
42            if emit == EmitFormat::Json {
43                eprintln!($($arg)*);
44            } else {
45                println!($($arg)*);
46            }
47        };
48    }
49
50    // Check if worktree already exists
51    let existing = git::find_worktree_by_branch(&repo, branch_name)?.or(
52        git::find_worktree_by_branch(&repo, &format!("refs/heads/{}", branch_name))?,
53    );
54
55    if let Some(existing_path) = existing {
56        say!(
57            "\n{}\nBranch '{}' already has a worktree at:\n  {}\n",
58            style("! Worktree already exists").yellow().bold(),
59            style(branch_name).cyan(),
60            style(existing_path.display()).blue(),
61        );
62
63        if git::is_non_interactive() {
64            return Err(CwError::InvalidBranch(format!(
65                "Worktree for branch '{}' already exists at {}.\n\
66                 Use 'gw resume {}' to continue work.",
67                branch_name,
68                existing_path.display(),
69                branch_name,
70            )));
71        }
72
73        // In interactive mode, suggest resume
74        say!(
75            "Use '{}' to resume work in this worktree.\n",
76            style(format!("gw resume {}", branch_name)).cyan()
77        );
78        return Ok(existing_path);
79    }
80
81    // Determine if branch already exists
82    let mut branch_already_exists = false;
83    let mut is_remote_only = false;
84
85    if git::branch_exists(branch_name, Some(&repo)) {
86        say!(
87            "\n{}\nBranch '{}' already exists locally but has no worktree.\n",
88            style("! Branch already exists").yellow().bold(),
89            style(branch_name).cyan(),
90        );
91        branch_already_exists = true;
92    } else if git::remote_branch_exists(branch_name, Some(&repo), "origin") {
93        say!(
94            "\n{}\nBranch '{}' exists on remote but not locally.\n",
95            style("! Remote branch found").yellow().bold(),
96            style(branch_name).cyan(),
97        );
98        branch_already_exists = true;
99        is_remote_only = true;
100    }
101
102    // Determine base branch
103    let base = if let Some(b) = base_branch {
104        b.to_string()
105    } else {
106        git::detect_default_branch(Some(&repo))
107    };
108
109    // Verify base branch
110    if (!is_remote_only || base_branch.is_some()) && !git::branch_exists(&base, Some(&repo)) {
111        return Err(CwError::InvalidBranch(messages::branch_not_found(&base)));
112    }
113
114    // Determine worktree path
115    let worktree_path = if let Some(p) = path {
116        PathBuf::from(p)
117            .canonicalize()
118            .unwrap_or_else(|_| PathBuf::from(p))
119    } else {
120        default_worktree_path(&repo, branch_name)
121    };
122
123    say!("\n{}", style("Creating new worktree:").cyan().bold());
124    say!("  Base branch: {}", style(&base).green());
125    say!("  New branch:  {}", style(branch_name).green());
126    say!("  Path:        {}\n", style(worktree_path.display()).blue());
127
128    // Create parent dir
129    if let Some(parent) = worktree_path.parent() {
130        let _ = std::fs::create_dir_all(parent);
131    }
132
133    // Fetch
134    let _ = git::git_command(&["fetch", "--all", "--prune"], Some(&repo), false, false);
135
136    // Create worktree
137    let wt_str = worktree_path.to_string_lossy().to_string();
138    if is_remote_only {
139        git::git_command(
140            &[
141                "worktree",
142                "add",
143                "-b",
144                branch_name,
145                &wt_str,
146                &format!("origin/{}", branch_name),
147            ],
148            Some(&repo),
149            true,
150            false,
151        )?;
152    } else if branch_already_exists {
153        git::git_command(
154            &["worktree", "add", &wt_str, branch_name],
155            Some(&repo),
156            true,
157            false,
158        )?;
159    } else {
160        git::git_command(
161            &["worktree", "add", "-b", branch_name, &wt_str, &base],
162            Some(&repo),
163            true,
164            false,
165        )?;
166    }
167
168    // Store metadata
169    let bb_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch_name);
170    let bp_key = format_config_key(CONFIG_KEY_BASE_PATH, branch_name);
171    let ib_key = format_config_key(CONFIG_KEY_INTENDED_BRANCH, branch_name);
172    git::set_config(&bb_key, &base, Some(&repo))?;
173    git::set_config(&bp_key, &repo.to_string_lossy(), Some(&repo))?;
174    git::set_config(&ib_key, branch_name, Some(&repo))?;
175
176    say!(
177        "{} Worktree created successfully\n",
178        style("*").green().bold()
179    );
180
181    // Copy shared files
182    shared_files::share_files(&repo, &worktree_path);
183
184    // post_new fires after the worktree is on disk, so a non-zero exit
185    // can't unwind the create. We propagate the error so the CLI exits
186    // non-zero (the standard `Error: ...` printer in `entrypoint::run`
187    // surfaces the cause); the worktree itself stays. The AI-tool launch
188    // is skipped because the user signalled "this worktree isn't ready."
189    crate::hooks::run_event("post_new", &worktree_path)?;
190
191    // --emit json: write the machine-readable result to stdout and skip spawn.
192    // The caller (hook or script) reads exactly this one line.
193    if emit == EmitFormat::Json {
194        println!(
195            "{}",
196            serde_json::to_string(&serde_json::json!({
197                "worktree_path": worktree_path.display().to_string(),
198                "branch": branch_name,
199                "base": base,
200            }))
201            .map_err(|e| CwError::Other(format!("json serialization failed: {e}")))?
202        );
203        return Ok(worktree_path);
204    }
205
206    // Launch AI tool in the new worktree. `-T skip|none|noop` (the
207    // replacement for the old `--no-term`) is handled inside
208    // spawn_in_worktree itself, so we always call through. Errors from the
209    // launcher are swallowed here: the worktree is on disk and usable
210    // either way, and the user can re-launch via `gw spawn`.
211    let _ = super::ai_tools::spawn_in_worktree(&worktree_path, initial_prompt, launch_opts);
212
213    Ok(worktree_path)
214}
215
216/// Outcome of attempting to delete a single worktree.
217///
218/// `delete_one` itself returns only `Deleted` or `Failed` today; `Skipped` is
219/// carried for the batch orchestrator, which may classify an entry as skipped
220/// before `delete_one` would even be called (see `rm_batch::PlanEntry`).
221#[derive(Debug)]
222pub enum DeletionOutcome {
223    Deleted {
224        branch: Option<String>,
225        path: PathBuf,
226    },
227    Skipped {
228        reason: String,
229    },
230    Failed {
231        error: CwError,
232    },
233}
234
235/// Flags that apply uniformly to every target in a batch.
236#[derive(Debug, Clone, Copy)]
237pub struct RmFlags {
238    pub keep_branch: bool,
239    pub delete_remote: bool,
240    /// Passes through to `git worktree remove --force` (historical semantic).
241    pub git_force: bool,
242    /// Bypass the busy-detection gate.
243    pub allow_busy: bool,
244}
245
246/// Per-target deletion. Assumes the caller has already resolved the target
247/// and decided to proceed (no summary, no batch confirmation, no busy prompt
248/// — the orchestrator handles those).
249///
250/// Returns an outcome describing what happened. Never prints a batch summary;
251/// individual progress lines are acceptable.
252pub(crate) fn delete_one(
253    worktree_path: &Path,
254    branch_name: Option<&str>,
255    main_repo: &Path,
256    flags: RmFlags,
257) -> DeletionOutcome {
258    // Safety: never delete the main worktree.
259    let wt_resolved = git::canonicalize_or(worktree_path);
260    let main_resolved = git::canonicalize_or(main_repo);
261    if wt_resolved == main_resolved {
262        return DeletionOutcome::Failed {
263            error: CwError::Git(messages::cannot_delete_main_worktree()),
264        };
265    }
266
267    // If cwd is inside worktree, move to main_repo before deletion.
268    if let Ok(cwd) = std::env::current_dir() {
269        let cwd_canon = cwd.canonicalize().unwrap_or(cwd);
270        let wt_canon = worktree_path
271            .canonicalize()
272            .unwrap_or_else(|_| worktree_path.to_path_buf());
273        if cwd_canon.starts_with(&wt_canon) {
274            let _ = std::env::set_current_dir(main_repo);
275        }
276    }
277
278    // pre_rm is advisory: a non-zero exit logs a warning but does not block
279    // removal. The historical "block on non-zero" contract was dropped to
280    // align with Claude Code's WorktreeRemove hook, which cannot block
281    // cleanup. `--force` bypasses busy detection only — never this hook.
282    if let Err(e) = crate::hooks::run_event("pre_rm", worktree_path) {
283        eprintln!(
284            "{} pre_rm hook failed (continuing anyway): {}",
285            style("!").yellow().bold(),
286            e
287        );
288    }
289
290    // Remove worktree
291    println!(
292        "{}",
293        style(messages::removing_worktree(worktree_path)).yellow()
294    );
295    if let Err(e) = git::remove_worktree_safe(worktree_path, main_repo, flags.git_force) {
296        return DeletionOutcome::Failed { error: e };
297    }
298    println!("{} Worktree removed\n", style("*").green().bold());
299
300    // Delete branch + metadata + optional remote push
301    if let Some(branch) = branch_name {
302        if !flags.keep_branch {
303            println!(
304                "{}",
305                style(messages::deleting_local_branch(branch)).yellow()
306            );
307            let _ = git::git_command(&["branch", "-D", branch], Some(main_repo), false, false);
308
309            let bb_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch);
310            let bp_key = format_config_key(CONFIG_KEY_BASE_PATH, branch);
311            let ib_key = format_config_key(CONFIG_KEY_INTENDED_BRANCH, branch);
312            git::unset_config(&bb_key, Some(main_repo));
313            git::unset_config(&bp_key, Some(main_repo));
314            git::unset_config(&ib_key, Some(main_repo));
315
316            println!(
317                "{} Local branch and metadata removed\n",
318                style("*").green().bold()
319            );
320
321            if flags.delete_remote {
322                println!(
323                    "{}",
324                    style(messages::deleting_remote_branch(branch)).yellow()
325                );
326                match git::git_command(
327                    &["push", "origin", &format!(":{}", branch)],
328                    Some(main_repo),
329                    false,
330                    true,
331                ) {
332                    Ok(r) if r.returncode == 0 => {
333                        println!("{} Remote branch deleted\n", style("*").green().bold());
334                    }
335                    _ => {
336                        println!("{} Remote branch deletion failed\n", style("!").yellow());
337                    }
338                }
339            }
340        }
341    }
342
343    DeletionOutcome::Deleted {
344        branch: branch_name.map(str::to_string),
345        path: worktree_path.to_path_buf(),
346    }
347}
348
349/// Delete a worktree by branch name, worktree directory name, or path.
350///
351/// # Parameters
352///
353/// * `force` — historical `git worktree remove --force` semantic. Forwarded
354///   to `git::remove_worktree_safe`; controls whether git itself will remove
355///   a worktree with uncommitted changes. Defaults to `true` at the CLI.
356/// * `allow_busy` — bypass the gw-level busy-detection gate (lockfile +
357///   process cwd scan). Wired to the explicit `--force` CLI flag on the
358///   delete subcommand so users can override "worktree is in use" refusals.
359///
360/// These two flags are intentionally separate: the CLI `--force` is an
361/// affirmative user choice to bypass the busy check, whereas the git-force
362/// behaviour is a long-standing default that users rarely flip off.
363pub fn delete_worktree(
364    target: Option<&str>,
365    keep_branch: bool,
366    delete_remote: bool,
367    force: bool,
368    allow_busy: bool,
369) -> Result<()> {
370    let main_repo = git::get_main_repo_root(None)?;
371    let (worktree_path, branch_name) = resolve_delete_target(target, &main_repo)?;
372
373    // Main-repo safety guard (mirrors delete_one, but we want the error
374    // surfaced up before prompting).
375    let wt_resolved = git::canonicalize_or(&worktree_path);
376    let main_resolved = git::canonicalize_or(&main_repo);
377    if wt_resolved == main_resolved {
378        return Err(CwError::Git(messages::cannot_delete_main_worktree()));
379    }
380
381    // If cwd is inside worktree, change to main repo *before* busy detection
382    // so the current process itself doesn't register as a busy holder.
383    // Canonicalize both sides so /var vs /private/var (macOS) and other
384    // symlink skew do not hide the match.
385    if let Ok(cwd) = std::env::current_dir() {
386        let cwd_canon = cwd.canonicalize().unwrap_or(cwd);
387        let wt_canon = worktree_path
388            .canonicalize()
389            .unwrap_or_else(|_| worktree_path.clone());
390        if cwd_canon.starts_with(&wt_canon) {
391            let _ = std::env::set_current_dir(&main_repo);
392        }
393    }
394
395    let (hard, soft) = crate::operations::busy::detect_busy_tiered(&worktree_path);
396    if (!hard.is_empty() || !soft.is_empty()) && !allow_busy {
397        let branch_display = branch_name.clone().unwrap_or_else(|| {
398            worktree_path
399                .file_name()
400                .map(|n| n.to_string_lossy().to_string())
401                .unwrap_or_else(|| worktree_path.to_string_lossy().to_string())
402        });
403        let msg = crate::operations::busy_messages::render_refusal(&branch_display, &hard, &soft);
404        eprint!("{}", msg);
405        return Err(CwError::Other(format!(
406            "worktree '{}' is in use; re-run with --force to override",
407            branch_display
408        )));
409    }
410
411    let flags = RmFlags {
412        keep_branch,
413        delete_remote,
414        git_force: force,
415        allow_busy: true, // already gated above
416    };
417
418    match delete_one(&worktree_path, branch_name.as_deref(), &main_repo, flags) {
419        DeletionOutcome::Deleted { .. } => Ok(()),
420        DeletionOutcome::Skipped { reason } => Err(CwError::Other(reason)),
421        DeletionOutcome::Failed { error } => Err(error),
422    }
423}
424
425/// Resolve delete target to (worktree_path, branch_name).
426///
427/// Uses strict ordered resolution: exact worktree name → exact branch → exact path.
428/// When `target` is `None`, falls back to cwd as the target path.
429fn resolve_delete_target(
430    target: Option<&str>,
431    main_repo: &Path,
432) -> Result<(PathBuf, Option<String>)> {
433    let target = target.map(|t| t.to_string()).unwrap_or_else(|| {
434        std::env::current_dir()
435            .unwrap_or_default()
436            .to_string_lossy()
437            .to_string()
438    });
439
440    let strict = super::helpers::resolve_target_strict(main_repo, &target)?;
441    Ok((strict.path, strict.branch))
442}