git-worktree-manager 0.1.2

Lean git worktree manager with AI coding-assistant integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/// Core worktree lifecycle operations.
///
use std::path::{Path, PathBuf};

use console::style;

use crate::constants::{
    default_worktree_path, format_config_key, CONFIG_KEY_BASE_BRANCH, CONFIG_KEY_BASE_PATH,
    CONFIG_KEY_INTENDED_BRANCH,
};
use crate::error::{CwError, Result};
use crate::git;
use crate::shared_files;

use crate::messages;

/// Create a new worktree with a feature branch.
pub fn create_worktree(
    branch_name: &str,
    base_branch: Option<&str>,
    path: Option<&str>,
    no_ai: bool,
    initial_prompt: Option<&str>,
    term_override: Option<&str>,
) -> Result<PathBuf> {
    let repo = git::get_repo_root(None)?;

    // Validate branch name
    if !git::is_valid_branch_name(branch_name, Some(&repo)) {
        let error_msg = git::get_branch_name_error(branch_name);
        return Err(CwError::InvalidBranch(messages::invalid_branch_name(
            &error_msg,
        )));
    }

    // Check if worktree already exists
    let existing = git::find_worktree_by_branch(&repo, branch_name)?.or(
        git::find_worktree_by_branch(&repo, &format!("refs/heads/{}", branch_name))?,
    );

    if let Some(existing_path) = existing {
        println!(
            "\n{}\nBranch '{}' already has a worktree at:\n  {}\n",
            style("! Worktree already exists").yellow().bold(),
            style(branch_name).cyan(),
            style(existing_path.display()).blue(),
        );

        if git::is_non_interactive() {
            return Err(CwError::InvalidBranch(format!(
                "Worktree for branch '{}' already exists at {}.\n\
                 Use 'gw resume {}' to continue work.",
                branch_name,
                existing_path.display(),
                branch_name,
            )));
        }

        // In interactive mode, suggest resume
        println!(
            "Use '{}' to resume work in this worktree.\n",
            style(format!("gw resume {}", branch_name)).cyan()
        );
        return Ok(existing_path);
    }

    // Determine if branch already exists
    let mut branch_already_exists = false;
    let mut is_remote_only = false;

    if git::branch_exists(branch_name, Some(&repo)) {
        println!(
            "\n{}\nBranch '{}' already exists locally but has no worktree.\n",
            style("! Branch already exists").yellow().bold(),
            style(branch_name).cyan(),
        );
        branch_already_exists = true;
    } else if git::remote_branch_exists(branch_name, Some(&repo), "origin") {
        println!(
            "\n{}\nBranch '{}' exists on remote but not locally.\n",
            style("! Remote branch found").yellow().bold(),
            style(branch_name).cyan(),
        );
        branch_already_exists = true;
        is_remote_only = true;
    }

    // Determine base branch
    let base = if let Some(b) = base_branch {
        b.to_string()
    } else {
        git::detect_default_branch(Some(&repo))
    };

    // Verify base branch
    if (!is_remote_only || base_branch.is_some()) && !git::branch_exists(&base, Some(&repo)) {
        return Err(CwError::InvalidBranch(messages::branch_not_found(&base)));
    }

    // Determine worktree path
    let worktree_path = if let Some(p) = path {
        PathBuf::from(p)
            .canonicalize()
            .unwrap_or_else(|_| PathBuf::from(p))
    } else {
        default_worktree_path(&repo, branch_name)
    };

    println!("\n{}", style("Creating new worktree:").cyan().bold());
    println!("  Base branch: {}", style(&base).green());
    println!("  New branch:  {}", style(branch_name).green());
    println!("  Path:        {}\n", style(worktree_path.display()).blue());

    // Create parent dir
    if let Some(parent) = worktree_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    // Fetch
    let _ = git::git_command(&["fetch", "--all", "--prune"], Some(&repo), false, false);

    // Create worktree
    let wt_str = worktree_path.to_string_lossy().to_string();
    if is_remote_only {
        git::git_command(
            &[
                "worktree",
                "add",
                "-b",
                branch_name,
                &wt_str,
                &format!("origin/{}", branch_name),
            ],
            Some(&repo),
            true,
            false,
        )?;
    } else if branch_already_exists {
        git::git_command(
            &["worktree", "add", &wt_str, branch_name],
            Some(&repo),
            true,
            false,
        )?;
    } else {
        git::git_command(
            &["worktree", "add", "-b", branch_name, &wt_str, &base],
            Some(&repo),
            true,
            false,
        )?;
    }

    // Store metadata
    let bb_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch_name);
    let bp_key = format_config_key(CONFIG_KEY_BASE_PATH, branch_name);
    let ib_key = format_config_key(CONFIG_KEY_INTENDED_BRANCH, branch_name);
    git::set_config(&bb_key, &base, Some(&repo))?;
    git::set_config(&bp_key, &repo.to_string_lossy(), Some(&repo))?;
    git::set_config(&ib_key, branch_name, Some(&repo))?;

    println!(
        "{} Worktree created successfully\n",
        style("*").green().bold()
    );

    // Copy shared files
    shared_files::share_files(&repo, &worktree_path);

    // post_new fires after the worktree is on disk, so a non-zero exit
    // can't unwind the create. We propagate the error so the CLI exits
    // non-zero (the standard `Error: ...` printer in `entrypoint::run`
    // surfaces the cause); the worktree itself stays. The AI-tool launch
    // is skipped because the user signalled "this worktree isn't ready."
    crate::hooks::run_event("post_new", &worktree_path)?;

    // Launch AI tool in the new worktree.
    if !no_ai {
        let _ = super::ai_tools::spawn_in_worktree(&worktree_path, initial_prompt, term_override);
    }

    Ok(worktree_path)
}

/// Outcome of attempting to delete a single worktree.
///
/// `delete_one` itself returns only `Deleted` or `Failed` today; `Skipped` is
/// carried for the batch orchestrator, which may classify an entry as skipped
/// before `delete_one` would even be called (see `rm_batch::PlanEntry`).
#[derive(Debug)]
pub enum DeletionOutcome {
    Deleted {
        branch: Option<String>,
        path: PathBuf,
    },
    Skipped {
        reason: String,
    },
    Failed {
        error: CwError,
    },
}

/// Flags that apply uniformly to every target in a batch.
#[derive(Debug, Clone, Copy)]
pub struct RmFlags {
    pub keep_branch: bool,
    pub delete_remote: bool,
    /// Passes through to `git worktree remove --force` (historical semantic).
    pub git_force: bool,
    /// Bypass the busy-detection gate.
    pub allow_busy: bool,
}

/// Per-target deletion. Assumes the caller has already resolved the target
/// and decided to proceed (no summary, no batch confirmation, no busy prompt
/// — the orchestrator handles those).
///
/// Returns an outcome describing what happened. Never prints a batch summary;
/// individual progress lines are acceptable.
pub(crate) fn delete_one(
    worktree_path: &Path,
    branch_name: Option<&str>,
    main_repo: &Path,
    flags: RmFlags,
) -> DeletionOutcome {
    // Safety: never delete the main worktree.
    let wt_resolved = git::canonicalize_or(worktree_path);
    let main_resolved = git::canonicalize_or(main_repo);
    if wt_resolved == main_resolved {
        return DeletionOutcome::Failed {
            error: CwError::Git(messages::cannot_delete_main_worktree()),
        };
    }

    // If cwd is inside worktree, move to main_repo before deletion.
    if let Ok(cwd) = std::env::current_dir() {
        let cwd_canon = cwd.canonicalize().unwrap_or(cwd);
        let wt_canon = worktree_path
            .canonicalize()
            .unwrap_or_else(|_| worktree_path.to_path_buf());
        if cwd_canon.starts_with(&wt_canon) {
            let _ = std::env::set_current_dir(main_repo);
        }
    }

    // pre_rm fires unconditionally — `--force` bypasses the busy-detection
    // gate, not the user's hook. A non-zero exit from the hook aborts the
    // remove (matches the README contract).
    if let Err(e) = crate::hooks::run_event("pre_rm", worktree_path) {
        return DeletionOutcome::Failed { error: e };
    }

    // Remove worktree
    println!(
        "{}",
        style(messages::removing_worktree(worktree_path)).yellow()
    );
    if let Err(e) = git::remove_worktree_safe(worktree_path, main_repo, flags.git_force) {
        return DeletionOutcome::Failed { error: e };
    }
    println!("{} Worktree removed\n", style("*").green().bold());

    // Delete branch + metadata + optional remote push
    if let Some(branch) = branch_name {
        if !flags.keep_branch {
            println!(
                "{}",
                style(messages::deleting_local_branch(branch)).yellow()
            );
            let _ = git::git_command(&["branch", "-D", branch], Some(main_repo), false, false);

            let bb_key = format_config_key(CONFIG_KEY_BASE_BRANCH, branch);
            let bp_key = format_config_key(CONFIG_KEY_BASE_PATH, branch);
            let ib_key = format_config_key(CONFIG_KEY_INTENDED_BRANCH, branch);
            git::unset_config(&bb_key, Some(main_repo));
            git::unset_config(&bp_key, Some(main_repo));
            git::unset_config(&ib_key, Some(main_repo));

            println!(
                "{} Local branch and metadata removed\n",
                style("*").green().bold()
            );

            if flags.delete_remote {
                println!(
                    "{}",
                    style(messages::deleting_remote_branch(branch)).yellow()
                );
                match git::git_command(
                    &["push", "origin", &format!(":{}", branch)],
                    Some(main_repo),
                    false,
                    true,
                ) {
                    Ok(r) if r.returncode == 0 => {
                        println!("{} Remote branch deleted\n", style("*").green().bold());
                    }
                    _ => {
                        println!("{} Remote branch deletion failed\n", style("!").yellow());
                    }
                }
            }
        }
    }

    DeletionOutcome::Deleted {
        branch: branch_name.map(str::to_string),
        path: worktree_path.to_path_buf(),
    }
}

/// Delete a worktree by branch name, worktree directory name, or path.
///
/// # Parameters
///
/// * `force` — historical `git worktree remove --force` semantic. Forwarded
///   to `git::remove_worktree_safe`; controls whether git itself will remove
///   a worktree with uncommitted changes. Defaults to `true` at the CLI.
/// * `allow_busy` — bypass the gw-level busy-detection gate (lockfile +
///   process cwd scan). Wired to the explicit `--force` CLI flag on the
///   delete subcommand so users can override "worktree is in use" refusals.
///
/// These two flags are intentionally separate: the CLI `--force` is an
/// affirmative user choice to bypass the busy check, whereas the git-force
/// behaviour is a long-standing default that users rarely flip off.
pub fn delete_worktree(
    target: Option<&str>,
    keep_branch: bool,
    delete_remote: bool,
    force: bool,
    allow_busy: bool,
) -> Result<()> {
    let main_repo = git::get_main_repo_root(None)?;
    let (worktree_path, branch_name) = resolve_delete_target(target, &main_repo)?;

    // Main-repo safety guard (mirrors delete_one, but we want the error
    // surfaced up before prompting).
    let wt_resolved = git::canonicalize_or(&worktree_path);
    let main_resolved = git::canonicalize_or(&main_repo);
    if wt_resolved == main_resolved {
        return Err(CwError::Git(messages::cannot_delete_main_worktree()));
    }

    // If cwd is inside worktree, change to main repo *before* busy detection
    // so the current process itself doesn't register as a busy holder.
    // Canonicalize both sides so /var vs /private/var (macOS) and other
    // symlink skew do not hide the match.
    if let Ok(cwd) = std::env::current_dir() {
        let cwd_canon = cwd.canonicalize().unwrap_or(cwd);
        let wt_canon = worktree_path
            .canonicalize()
            .unwrap_or_else(|_| worktree_path.clone());
        if cwd_canon.starts_with(&wt_canon) {
            let _ = std::env::set_current_dir(&main_repo);
        }
    }

    let (hard, soft) = crate::operations::busy::detect_busy_tiered(&worktree_path);
    if (!hard.is_empty() || !soft.is_empty()) && !allow_busy {
        let branch_display = branch_name.clone().unwrap_or_else(|| {
            worktree_path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| worktree_path.to_string_lossy().to_string())
        });
        let msg = crate::operations::busy_messages::render_refusal(&branch_display, &hard, &soft);
        eprint!("{}", msg);
        return Err(CwError::Other(format!(
            "worktree '{}' is in use; re-run with --force to override",
            branch_display
        )));
    }

    let flags = RmFlags {
        keep_branch,
        delete_remote,
        git_force: force,
        allow_busy: true, // already gated above
    };

    match delete_one(&worktree_path, branch_name.as_deref(), &main_repo, flags) {
        DeletionOutcome::Deleted { .. } => Ok(()),
        DeletionOutcome::Skipped { reason } => Err(CwError::Other(reason)),
        DeletionOutcome::Failed { error } => Err(error),
    }
}

/// Resolve delete target to (worktree_path, branch_name).
///
/// Uses strict ordered resolution: exact worktree name → exact branch → exact path.
/// When `target` is `None`, falls back to cwd as the target path.
fn resolve_delete_target(
    target: Option<&str>,
    main_repo: &Path,
) -> Result<(PathBuf, Option<String>)> {
    let target = target.map(|t| t.to_string()).unwrap_or_else(|| {
        std::env::current_dir()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string()
    });

    let strict = super::helpers::resolve_target_strict(main_repo, &target)?;
    Ok((strict.path, strict.branch))
}