workmux 0.1.173

An opinionated workflow tool that orchestrates git worktrees and tmux
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use crate::multiplexer::{create_backend, detect_backend};
use crate::workflow::WorkflowContext;
use crate::{config, git, spinner, workflow};
use anyhow::{Context, Result, anyhow};
use std::io::{self, Write};
use std::path::PathBuf;

pub fn run(
    names: Vec<String>,
    gone: bool,
    all: bool,
    force: bool,
    keep_branch: bool,
) -> Result<()> {
    if all {
        return run_all(force, keep_branch);
    }

    if gone {
        return run_gone(force, keep_branch);
    }

    run_specified(names, force, keep_branch)
}

/// Remove specific worktrees provided by user (or current if empty)
fn run_specified(names: Vec<String>, force: bool, keep_branch: bool) -> Result<()> {
    // Normalize all inputs (handles "." and other special cases)
    let resolved_names: Vec<String> = if names.is_empty() {
        vec![super::resolve_name(None)?]
    } else {
        names
            .iter()
            .map(|n| super::resolve_name(Some(n)))
            .collect::<Result<Vec<_>>>()?
    };

    // 2. Resolve all targets and validate they exist
    let mut candidates: Vec<(String, PathBuf, String)> = Vec::new();
    for name in resolved_names {
        let (worktree_path, branch_name) = git::find_worktree(&name)
            .with_context(|| format!("No worktree found with name '{}'", name))?;

        let handle = worktree_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| {
                anyhow!(
                    "Could not derive handle from worktree path: {:?}",
                    worktree_path
                )
            })?
            .to_string();

        candidates.push((handle, worktree_path, branch_name));
    }

    // 3. If forced, skip all checks and remove
    if force {
        let mut failed: Vec<(String, String)> = Vec::new();

        for (handle, _, _) in candidates {
            if let Err(e) = remove_worktree(&handle, true, keep_branch) {
                failed.push((handle, e.to_string()));
            }
        }

        if !failed.is_empty() {
            eprintln!("\nFailed to remove {} worktree(s):", failed.len());
            for (handle, error) in &failed {
                eprintln!("  - {}: {}", handle, error);
            }
            return Err(anyhow!("Some worktrees could not be removed"));
        }

        return Ok(());
    }

    // 4. Safety checks: categorize candidates
    let mut uncommitted: Vec<String> = Vec::new();
    let mut unmerged: Vec<(String, String, String)> = Vec::new(); // (handle, branch, base)
    let mut safe: Vec<String> = Vec::new();

    for (handle, path, branch) in candidates {
        // Check uncommitted (blocking)
        if path.exists() && git::has_uncommitted_changes(&path).unwrap_or(false) {
            uncommitted.push(handle);
            continue;
        }

        // Check unmerged (promptable), only if we're deleting the branch
        if !keep_branch && let Some(base) = is_unmerged(&branch)? {
            unmerged.push((handle, branch, base));
            continue;
        }

        safe.push(handle);
    }

    // 5. Handle blocking issues (uncommitted changes)
    if !uncommitted.is_empty() {
        eprintln!("The following worktrees have uncommitted changes:");
        for handle in &uncommitted {
            eprintln!("  - {}", handle);
        }
        return Err(anyhow!(
            "Cannot remove worktrees with uncommitted changes. Use --force to override."
        ));
    }

    // 6. Handle warnings (unmerged branches)
    if !unmerged.is_empty() {
        println!("The following branches have commits not merged into their base:");
        for (_, branch, base) in &unmerged {
            println!("  - {} (base: {})", branch, base);
        }
        println!("\nThis will delete the worktree, tmux window, and local branch.");
        print!("Are you sure you want to continue? [y/N] ");
        io::stdout().flush().context("Failed to flush stdout")?;

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .context("Failed to read input")?;

        if input.trim().to_lowercase() != "y" {
            println!("Aborted.");
            return Ok(());
        }

        // Add unmerged candidates to safe list for processing
        for (handle, _, _) in unmerged {
            safe.push(handle);
        }
    }

    // 7. Execute removal
    for handle in safe {
        // force=true because we already checked/prompted
        remove_worktree(&handle, true, keep_branch)?;
    }

    Ok(())
}

/// Check if a branch has unmerged commits. Returns Some(base) if unmerged, None otherwise.
fn is_unmerged(branch: &str) -> Result<Option<String>> {
    let main_branch = git::get_default_branch().unwrap_or_else(|_| "main".to_string());

    let base = git::get_branch_base(branch)
        .ok()
        .unwrap_or_else(|| main_branch.clone());

    let base_commit = match git::get_merge_base(&base) {
        Ok(b) => b,
        Err(_) => {
            // If we can't determine base, try falling back to main
            match git::get_merge_base(&main_branch) {
                Ok(b) => b,
                Err(_) => return Ok(None), // Can't determine, assume safe
            }
        }
    };

    let unmerged_branches = git::get_unmerged_branches(&base_commit)?;
    if unmerged_branches.contains(branch) {
        Ok(Some(base))
    } else {
        Ok(None)
    }
}

/// Remove all managed worktrees (except main)
fn run_all(force: bool, keep_branch: bool) -> Result<()> {
    let worktrees = git::list_worktrees()?;
    let main_branch = git::get_default_branch()?;
    let main_worktree_root = git::get_main_worktree_root()?;

    let mut to_remove: Vec<(PathBuf, String, String)> = Vec::new();
    let mut skipped_uncommitted: Vec<String> = Vec::new();
    let mut skipped_unmerged: Vec<String> = Vec::new();

    for (path, branch) in worktrees {
        // Skip main branch/worktree and detached HEAD
        if branch == main_branch || branch == "(detached)" {
            continue;
        }

        // Skip the main worktree itself (safety check)
        if path == main_worktree_root {
            continue;
        }

        // Check for uncommitted changes
        if !force && path.exists() && git::has_uncommitted_changes(&path).unwrap_or(false) {
            skipped_uncommitted.push(branch);
            continue;
        }

        // Check for unmerged commits (only when deleting the branch)
        if !force && !keep_branch {
            let base = git::get_branch_base(&branch)
                .ok()
                .unwrap_or_else(|| main_branch.clone());
            if let Ok(merge_base) = git::get_merge_base(&base)
                && let Ok(unmerged_branches) = git::get_unmerged_branches(&merge_base)
                && unmerged_branches.contains(&branch)
            {
                skipped_unmerged.push(branch);
                continue;
            }
        }

        let handle = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&branch)
            .to_string();

        to_remove.push((path, branch, handle));
    }

    if to_remove.is_empty() && skipped_uncommitted.is_empty() && skipped_unmerged.is_empty() {
        println!("No worktrees to remove.");
        return Ok(());
    }

    if to_remove.is_empty() {
        println!("No removable worktrees found.");
        if !skipped_uncommitted.is_empty() {
            println!(
                "\nSkipped {} worktree(s) with uncommitted changes:",
                skipped_uncommitted.len()
            );
            for branch in &skipped_uncommitted {
                println!("  - {}", branch);
            }
        }
        if !skipped_unmerged.is_empty() {
            println!(
                "\nSkipped {} worktree(s) with unmerged commits:",
                skipped_unmerged.len()
            );
            for branch in &skipped_unmerged {
                println!("  - {}", branch);
            }
        }
        println!("\nUse --force to remove these anyway.");
        return Ok(());
    }

    // Show what will be removed
    println!("The following worktrees will be removed:");
    for (_, branch, _) in &to_remove {
        println!("  - {}", branch);
    }

    if !skipped_uncommitted.is_empty() {
        println!(
            "\nSkipping {} worktree(s) with uncommitted changes:",
            skipped_uncommitted.len()
        );
        for branch in &skipped_uncommitted {
            println!("  - {}", branch);
        }
    }

    if !skipped_unmerged.is_empty() {
        println!(
            "\nSkipping {} worktree(s) with unmerged commits:",
            skipped_unmerged.len()
        );
        for branch in &skipped_unmerged {
            println!("  - {}", branch);
        }
    }

    // Confirm with user unless --force
    if !force {
        print!(
            "\nAre you sure you want to remove ALL {} worktree(s)? [y/N] ",
            to_remove.len()
        );
        io::stdout().flush().context("Failed to flush stdout")?;

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .context("Failed to read user input")?;

        if input.trim().to_lowercase() != "y" {
            println!("Aborted.");
            return Ok(());
        }
    }

    // Execute removal
    let mut success_count = 0;
    let mut failed: Vec<(String, String)> = Vec::new();

    for (_, branch, handle) in to_remove {
        match remove_worktree(&handle, true, keep_branch) {
            Ok(()) => success_count += 1,
            Err(e) => failed.push((branch, e.to_string())),
        }
    }

    // Report results
    if success_count > 0 {
        println!("\n✓ Successfully removed {} worktree(s)", success_count);
    }

    if !failed.is_empty() {
        eprintln!("\nFailed to remove {} worktree(s):", failed.len());
        for (branch, error) in &failed {
            eprintln!("  - {}: {}", branch, error);
        }
    }

    Ok(())
}

/// Remove worktrees whose upstream remote branch has been deleted
fn run_gone(force: bool, keep_branch: bool) -> Result<()> {
    // Fetch with prune to update remote-tracking refs
    spinner::with_spinner("Fetching from remote", git::fetch_prune)?;

    let worktrees = git::list_worktrees()?;
    let main_branch = git::get_default_branch()?;
    let main_worktree_root = git::get_main_worktree_root()?;

    let gone_branches = git::get_gone_branches().unwrap_or_default();

    // Find worktrees whose upstream is gone
    let mut to_remove: Vec<(PathBuf, String, String)> = Vec::new();
    let mut skipped_uncommitted: Vec<String> = Vec::new();

    for (path, branch) in worktrees {
        // Skip main branch/worktree and detached HEAD
        if branch == main_branch || branch == "(detached)" {
            continue;
        }

        // Skip the main worktree itself
        if path == main_worktree_root {
            continue;
        }

        // Check if upstream is gone
        if !gone_branches.contains(&branch) {
            continue;
        }

        // Check for uncommitted changes
        if !force && path.exists() && git::has_uncommitted_changes(&path).unwrap_or(false) {
            skipped_uncommitted.push(branch);
            continue;
        }

        let handle = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&branch)
            .to_string();

        to_remove.push((path, branch, handle));
    }

    if to_remove.is_empty() && skipped_uncommitted.is_empty() {
        println!("No worktrees with gone upstreams found.");
        return Ok(());
    }

    if to_remove.is_empty() {
        println!("No worktrees to remove.");
        if !skipped_uncommitted.is_empty() {
            println!(
                "\nSkipped {} worktree(s) with uncommitted changes:",
                skipped_uncommitted.len()
            );
            for branch in &skipped_uncommitted {
                println!("  - {}", branch);
            }
            println!("\nUse --force to remove these anyway.");
        }
        return Ok(());
    }

    // Show what will be removed
    println!("The following worktrees have gone upstreams and will be removed:");
    for (_, branch, _) in &to_remove {
        println!("  - {}", branch);
    }

    if !skipped_uncommitted.is_empty() {
        println!(
            "\nSkipping {} worktree(s) with uncommitted changes:",
            skipped_uncommitted.len()
        );
        for branch in &skipped_uncommitted {
            println!("  - {}", branch);
        }
    }

    // Confirm with user unless --force
    if !force {
        print!(
            "\nAre you sure you want to remove {} worktree(s)? [y/N] ",
            to_remove.len()
        );
        io::stdout().flush().context("Failed to flush stdout")?;

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .context("Failed to read user input")?;

        if input.trim().to_lowercase() != "y" {
            println!("Aborted.");
            return Ok(());
        }
    }

    // Execute removal
    let mut success_count = 0;
    let mut failed: Vec<(String, String)> = Vec::new();

    for (_, branch, handle) in to_remove {
        match remove_worktree(&handle, true, keep_branch) {
            Ok(()) => success_count += 1,
            Err(e) => failed.push((branch, e.to_string())),
        }
    }

    // Report results
    if success_count > 0 {
        println!("\n✓ Successfully removed {} worktree(s)", success_count);
    }

    if !failed.is_empty() {
        eprintln!("\nFailed to remove {} worktree(s):", failed.len());
        for (branch, error) in &failed {
            eprintln!("  - {}: {}", branch, error);
        }
    }

    Ok(())
}

/// Execute the actual worktree removal
fn remove_worktree(handle: &str, force: bool, keep_branch: bool) -> Result<()> {
    let config = config::Config::load(None)?;
    let mux = create_backend(detect_backend());
    let context = WorkflowContext::new(config, mux, None)?;

    super::announce_hooks(&context.config, None, super::HookPhase::PreRemove);

    let result = workflow::remove(handle, force, keep_branch, &context)
        .context("Failed to remove worktree")?;

    if keep_branch {
        println!(
            "✓ Removed worktree '{}' (branch '{}' kept)",
            handle, result.branch_removed
        );
    } else {
        println!(
            "✓ Removed worktree '{}' and branch '{}'",
            handle, result.branch_removed
        );
    }

    Ok(())
}