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
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
475
//! CLI entrypoint — shared between the `gw` and `cw` binaries.
//!
//! Both binary targets (`src/bin/gw.rs`, `src/bin/cw.rs`) delegate to
//! [`run`]. Keeping the logic here avoids compiling the same source file
//! twice, which triggered Cargo's "file present in multiple build targets"
//! warning under the previous layout.

use clap::Parser;

use crate::cli::{Cli, Commands};
use crate::config;
use crate::console as cwconsole;
use crate::constants;
use crate::cwshare_setup;
use crate::error::{CwError, Result};
use crate::operations::{
    ai_tools, diagnostics, display, exec, guard, helpers, path_cmd, run, setup_claude, spawn_spec,
    worktree,
};
use crate::resolve_prompt;
use crate::shell_functions;
use crate::tui;
use crate::update;
use std::io::Read;

pub fn run() {
    tui::install_panic_hook();
    let cli = Cli::parse();

    if let Some(ref shell_name) = cli.generate_completion {
        generate_completions(shell_name);
        return;
    }

    // Skip startup checks for internal commands (shell-completion helpers,
    // cache refresh) — they are invoked by the shell on every keystroke, so
    // paying for update-check / prompts would compound latency and risk
    // recursive re-entry into the update flow.
    let is_internal = matches!(
        &cli.command,
        Some(
            Commands::UpdateCache
                | Commands::CompleteTargets
                | Commands::Path { .. }
                | Commands::ShellFunction { .. }
                | Commands::SpawnAi { .. }
                | Commands::Guard { .. }
        )
    );

    if !is_internal {
        crate::operations::spawn_spec::sweep_stale();
        update::check_for_update_if_needed();
    }

    if !is_internal {
        config::prompt_shell_completion_setup();
    }

    let result = match cli.command {
        Some(Commands::List) => display::list_worktrees(),
        Some(Commands::Ls) => display::list_worktrees_tsv(),
        Some(Commands::New {
            name,
            path,
            base,
            no_term,
            term,
            prompt,
            prompt_file,
            prompt_stdin,
        }) => (|| -> Result<()> {
            // Resolve the prompt first so a missing file or unreadable stdin
            // fails before any interactive side effects (worktree creation,
            // AI-tool launch) leave the tree in a half-configured state.
            let resolved = resolve_prompt(prompt, prompt_file.as_deref(), prompt_stdin, || {
                let mut buf = String::new();
                std::io::stdin().read_to_string(&mut buf)?;
                Ok(buf)
            })?;
            // Pre-flight `-T <method>` so a typo (`-T does-not-exist`) errors
            // before we create a worktree on disk. The launch path inside
            // create_worktree swallows spawn errors with `let _ = …`, which
            // would otherwise leave a phantom worktree on a bad alias.
            if !no_term {
                let _ = config::parse_term_option(term.as_deref())?;
            }
            cwshare_setup::prompt_cwshare_setup();

            worktree::create_worktree(
                &name,
                base.as_deref(),
                path.as_deref(),
                no_term,
                resolved.as_deref(),
                term.as_deref(),
            )?;
            Ok(())
        })(),

        Some(Commands::Resume { branch, term }) => {
            ai_tools::resume_worktree(branch.as_deref(), term.as_deref())
        }

        Some(Commands::Spawn {
            target,
            term,
            prompt,
            prompt_file,
            prompt_stdin,
        }) => (|| -> Result<()> {
            let resolved_prompt =
                resolve_prompt(prompt, prompt_file.as_deref(), prompt_stdin, || {
                    let mut buf = String::new();
                    std::io::stdin().read_to_string(&mut buf)?;
                    Ok(buf)
                })?;
            let cwd = std::env::current_dir()?;
            let target_path = match target {
                Some(t) => {
                    let main_repo = crate::git::get_main_repo_root(Some(&cwd))?;
                    helpers::resolve_target_strict(&main_repo, &t)?.path
                }
                None => crate::git::get_repo_root(Some(&cwd))?,
            };
            ai_tools::spawn_in_worktree(&target_path, resolved_prompt.as_deref(), term.as_deref())
        })(),

        Some(Commands::Rm {
            targets,
            interactive,
            dry_run,
            keep_branch,
            delete_remote,
            force,
            no_force,
        }) => {
            let flags = crate::operations::worktree::RmFlags {
                keep_branch,
                delete_remote,
                git_force: !no_force,
                allow_busy: force,
            };
            match crate::operations::rm_batch::rm_worktrees(targets, interactive, dry_run, flags) {
                Ok(0) => Ok(()),
                Ok(code) => Err(crate::error::CwError::ExitCode(code)),
                Err(e) => Err(e),
            }
        }

        Some(Commands::Doctor {
            session_start,
            quiet,
        }) => diagnostics::doctor(session_start, quiet),
        Some(Commands::Run {
            only,
            no_main,
            jobs,
            continue_on_error,
            cmd,
        }) => (|| -> Result<()> {
            let cwd = std::env::current_dir()?;
            let code = run::run_in_scope(
                &cwd,
                &cmd,
                only.as_deref(),
                no_main,
                jobs,
                continue_on_error,
            )?;
            if code != 0 {
                return Err(crate::error::CwError::ExitCode(code));
            }
            Ok(())
        })(),

        Some(Commands::Exec { target, cmd }) => (|| -> Result<()> {
            let cwd = std::env::current_dir()?;
            let mut out = std::io::stdout().lock();
            let code = exec::exec_in_target(&cwd, &target, &cmd, &mut out)?;
            if code != 0 {
                return Err(crate::error::CwError::ExitCode(code));
            }
            Ok(())
        })(),

        Some(Commands::Guard { tool_input }) => guard::run(&tool_input),
        Some(Commands::SetupClaude) => setup_claude::setup_claude(),

        Some(Commands::Upgrade { yes }) => {
            update::upgrade(yes);
            Ok(())
        }

        Some(Commands::ShellSetup) => {
            shell_setup();
            Ok(())
        }

        Some(Commands::Path {
            branch,
            list_branches,
            interactive,
        }) => path_cmd::worktree_path(branch.as_deref(), list_branches, interactive),

        Some(Commands::ShellFunction { shell }) => match shell_functions::generate(&shell) {
            Some(output) => {
                print!("{}", output);
                Ok(())
            }
            None => Err(CwError::Config(format!(
                "Unsupported shell: {}. Use bash, zsh, fish, or powershell.",
                shell
            ))),
        },

        Some(Commands::UpdateCache) => {
            update::refresh_cache();
            Ok(())
        }

        Some(Commands::CompleteTargets) => crate::operations::complete::print_completion_targets(),

        Some(Commands::SpawnAi { spec }) => {
            // Pre-spawn failures (read/parse/chdir) exit 127 — the shell
            // "command not found / could not start" convention. Post-spawn
            // failures exit from inside `execute` directly, also with 127.
            // Inner errors already carry the "spawn-ai:" prefix via their
            // CwError::Other messages, so we print them verbatim.
            let resolved = match spec {
                Some(p) => p,
                None => match spawn_spec::resolve_last_for_cwd() {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!("{}", e);
                        std::process::exit(127);
                    }
                },
            };
            if let Err(e) = spawn_spec::execute(&resolved) {
                eprintln!("{}", e);
                std::process::exit(127);
            }
            Ok(())
        }

        None => Ok(()),
    };

    if let Err(e) = result {
        // ExitCode carries a specific exit status from callers that have
        // already produced their own user-facing output (e.g. the multi-target
        // delete orchestrator). Exit silently with that code instead of the
        // generic "Error: …" print.
        if let CwError::ExitCode(code) = e {
            std::process::exit(code);
        }
        cwconsole::print_error(&format!("Error: {}", e));
        std::process::exit(1);
    }
}

fn generate_completions(shell_name: &str) {
    use clap::CommandFactory;
    use clap_complete::{generate, Shell};

    let shell = match shell_name.to_lowercase().as_str() {
        "bash" => Shell::Bash,
        "zsh" => Shell::Zsh,
        "fish" => Shell::Fish,
        "powershell" | "pwsh" => Shell::PowerShell,
        "elvish" => Shell::Elvish,
        _ => {
            eprintln!(
                "Unsupported shell: {}. Use bash, zsh, fish, powershell, or elvish.",
                shell_name
            );
            std::process::exit(1);
        }
    };

    let mut cmd = Cli::command();
    generate(shell, &mut cmd, "gw", &mut std::io::stdout());
}

fn shell_setup() {
    let shell_env = std::env::var("SHELL").unwrap_or_default();
    let is_powershell = cfg!(target_os = "windows") || std::env::var("PSModulePath").is_ok();

    let home = constants::home_dir_or_fallback();
    let (shell_name, profile_path) = if shell_env.contains("zsh") {
        ("zsh", Some(home.join(".zshrc")))
    } else if shell_env.contains("bash") {
        ("bash", Some(home.join(".bashrc")))
    } else if shell_env.contains("fish") {
        (
            "fish",
            Some(home.join(".config").join("fish").join("config.fish")),
        )
    } else if is_powershell {
        ("powershell", None::<std::path::PathBuf>)
    } else {
        println!("Could not detect your shell automatically.\n");
        println!("Please manually add the gw-cd function to your shell:\n");
        println!("  bash/zsh:    source <(gw _shell-function bash)");
        println!("  fish:        gw _shell-function fish | source");
        println!("  PowerShell:  gw _shell-function powershell | Out-String | Invoke-Expression");
        return;
    };

    println!("Detected shell: {}\n", shell_name);

    if shell_name == "powershell" {
        println!("To enable gw-cd in PowerShell, add the following to your $PROFILE:\n");
        println!("  gw _shell-function powershell | Out-String | Invoke-Expression\n");
        println!("To find your PowerShell profile location, run: $PROFILE");
        println!(
            "\nIf the profile file doesn't exist, create it with: New-Item -Path $PROFILE -ItemType File -Force"
        );
        return;
    }

    let shell_function_line = match shell_name {
        "fish" => "gw _shell-function fish | source".to_string(),
        _ => format!("source <(gw _shell-function {})", shell_name),
    };

    if let Some(ref path) = profile_path {
        if path.exists() {
            if let Ok(content) = std::fs::read_to_string(path) {
                if content.contains("gw _shell-function") || content.contains("gw-cd") {
                    println!(
                        "{}",
                        console::style("Shell integration is already installed.").green()
                    );
                    println!("  Found in: {}\n", path.display());

                    refresh_shell_cache(shell_name);

                    println!("\nRestart your shell or run: source {}", path.display());
                    return;
                }
            }
        }
    }

    println!("Setup shell integration?\n");
    println!(
        "This will add the following to {}:",
        profile_path
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or("your profile".to_string())
    );

    println!(
        "\n  # git-worktree-manager shell integration{}",
        if matches!(shell_name, "zsh" | "bash") {
            " (gw-cd + tab completion)"
        } else {
            ""
        }
    );
    println!("  {}\n", shell_function_line);

    print!("Add to your shell profile? [Y/n]: ");
    use std::io::Write;
    let _ = std::io::stdout().flush();

    let mut input = String::new();
    let _ = std::io::stdin().read_line(&mut input);
    let input = input.trim().to_lowercase();

    if !input.is_empty() && input != "y" && input != "yes" {
        println!("\nSetup cancelled.");
        return;
    }

    let Some(ref path) = profile_path else {
        return;
    };

    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    let comment_suffix = if matches!(shell_name, "zsh" | "bash") {
        " (gw-cd + tab completion)"
    } else {
        ""
    };
    let append = format!(
        "\n# git-worktree-manager shell integration{}\n{}\n",
        comment_suffix, shell_function_line
    );

    match std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
    {
        Ok(mut f) => {
            let _ = f.write_all(append.as_bytes());

            if let Ok(mut cfg) = config::load_config() {
                cfg.shell_completion.installed = true;
                cfg.shell_completion.prompted = true;
                let _ = config::save_config(&cfg);
            }

            println!("\n* Successfully added to {}", path.display());

            refresh_shell_cache(shell_name);

            println!("\nNext steps:");
            println!("  1. Restart your shell or run: source {}", path.display());
            println!("  2. Try directory navigation: gw-cd <branch-name>");
            println!("  3. Try tab completion: gw <TAB> or gw new <TAB>");
        }
        Err(e) => {
            println!("\nError: Failed to update {}: {}", path.display(), e);
            println!("\nTo install manually, add the lines shown above to your profile");
        }
    }
}

/// Refresh cached shell function files to pick up new features.
fn refresh_shell_cache(shell_name: &str) {
    let home = constants::home_dir_or_fallback();

    let cache_paths = [
        home.join(".cache").join("gw-shell-function.zsh"),
        home.join(".cache").join("gw-shell-function.bash"),
        home.join(".cache").join("gw-shell-function.fish"),
    ];

    let mut refreshed = false;
    for cache_path in &cache_paths {
        if !cache_path.exists() {
            continue;
        }
        let cache_shell = cache_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        if let Some(content) = shell_functions::generate(cache_shell) {
            if std::fs::write(cache_path, content).is_ok() {
                println!(
                    "  {} {}",
                    console::style("Refreshed cache:").dim(),
                    cache_path.display()
                );
                refreshed = true;
            }
        }
    }

    if refreshed {
        return;
    }

    let cache_path = home
        .join(".cache")
        .join(format!("gw-shell-function.{}", shell_name));
    if let Some(content) = shell_functions::generate(shell_name) {
        let _ = std::fs::create_dir_all(cache_path.parent().unwrap_or(&home));
        if std::fs::write(&cache_path, &content).is_ok() {
            println!(
                "  {} {}",
                console::style("Created cache:").dim(),
                cache_path.display()
            );
        }
    }
}