git-worktree-manager 0.0.31

CLI tool integrating git worktree with AI coding assistants
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
/// CLI definitions using clap derive.
///
/// Mirrors the Typer-based CLI in src/git_worktree_manager/cli.py.
pub mod completions;
pub mod global;

use clap::{Args, Parser, Subcommand, ValueHint};

/// Shared cache-bypass flag, flattened into subcommands that query PR status.
#[derive(Args, Debug, Clone)]
pub struct CacheControl {
    /// Bypass PR status cache (60s TTL) and refresh from gh
    #[arg(long)]
    pub no_cache: bool,
}

/// Validate config key (accepts any string but provides completion hints).
fn parse_config_key(s: &str) -> Result<String, String> {
    Ok(s.to_string())
}

/// Parse duration strings like "30", "30d", "2w", "1m" into days.
fn parse_duration_days(s: &str) -> Result<u64, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty duration".into());
    }

    // Pure number = days
    if let Ok(n) = s.parse::<u64>() {
        return Ok(n);
    }

    let (num_str, suffix) = s.split_at(s.len() - 1);
    let n: u64 = num_str
        .parse()
        .map_err(|_| format!("invalid duration: '{}'. Use e.g. 30, 7d, 2w, 1m", s))?;

    match suffix {
        "d" => Ok(n),
        "w" => Ok(n * 7),
        "m" => Ok(n * 30),
        "y" => Ok(n * 365),
        _ => Err(format!(
            "unknown duration suffix '{}'. Use d (days), w (weeks), m (months), y (years)",
            suffix
        )),
    }
}

/// Git worktree manager CLI.
#[derive(Parser, Debug)]
#[command(
    name = "gw",
    version,
    about = "git worktree manager — AI coding assistant integration",
    long_about = None,
    arg_required_else_help = true,
)]
pub struct Cli {
    /// Run in global mode (across all registered repositories)
    #[arg(short = 'g', long = "global", global = true)]
    pub global: bool,

    /// Generate shell completions for the given shell
    #[arg(long, value_name = "SHELL", value_parser = clap::builder::PossibleValuesParser::new(["bash", "zsh", "fish", "powershell", "elvish"]))]
    pub generate_completion: Option<String>,

    #[command(subcommand)]
    pub command: Option<Commands>,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Create new worktree for feature branch
    New {
        /// Branch name for the new worktree
        name: String,

        /// Custom worktree path (default: ../<repo>-<branch>)
        #[arg(short, long, value_hint = ValueHint::DirPath)]
        path: Option<String>,

        /// Base branch to create from (default: from config)
        #[arg(short = 'b', long = "base")]
        base: Option<String>,

        /// Skip AI tool launch
        #[arg(long = "no-term")]
        no_term: bool,

        /// Terminal launch method (e.g., tmux, iterm-tab, zellij)
        #[arg(short = 'T', long)]
        term: Option<String>,

        /// Launch AI tool in background
        #[arg(long)]
        bg: bool,

        /// Initial prompt to pass to the AI tool (starts interactive session with task)
        #[arg(long)]
        prompt: Option<String>,
    },

    /// Create GitHub Pull Request from worktree
    Pr {
        /// Branch name (default: current worktree branch)
        branch: Option<String>,

        /// PR title
        #[arg(short, long)]
        title: Option<String>,

        /// PR body
        #[arg(short = 'B', long)]
        body: Option<String>,

        /// Create as draft PR
        #[arg(short, long)]
        draft: bool,

        /// Skip pushing to remote
        #[arg(long)]
        no_push: bool,

        /// Resolve target as worktree name (instead of branch)
        #[arg(short, long)]
        worktree: bool,

        /// Resolve target as branch name (instead of worktree)
        #[arg(short = 'b', long = "by-branch", conflicts_with = "worktree")]
        by_branch: bool,
    },

    /// Merge feature branch into base branch
    Merge {
        /// Branch name (default: current worktree branch)
        branch: Option<String>,

        /// Interactive rebase
        #[arg(short, long)]
        interactive: bool,

        /// Dry run (show what would happen)
        #[arg(long)]
        dry_run: bool,

        /// Push to remote after merge
        #[arg(long)]
        push: bool,

        /// Use AI to resolve merge conflicts
        #[arg(long)]
        ai_merge: bool,

        /// Resolve target as worktree name (instead of branch)
        #[arg(short, long)]
        worktree: bool,
    },

    /// Resume AI work in a worktree
    Resume {
        /// Branch name to resume (default: current worktree)
        branch: Option<String>,

        /// Terminal launch method
        #[arg(short = 'T', long)]
        term: Option<String>,

        /// Launch AI tool in background
        #[arg(long)]
        bg: bool,

        /// Resolve target as worktree name (instead of branch)
        #[arg(short, long)]
        worktree: bool,

        /// Resolve target as branch name (instead of worktree)
        #[arg(short, long, conflicts_with = "worktree")]
        by_branch: bool,
    },

    /// Open interactive shell or execute command in a worktree
    Shell {
        /// Worktree branch to shell into
        worktree: Option<String>,

        /// Command and arguments to execute
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Show current worktree status
    Status {
        #[command(flatten)]
        cache: CacheControl,
    },

    /// Delete a worktree
    Delete {
        /// Branch name or path of worktree to delete (default: current worktree)
        target: Option<String>,

        /// Keep the branch (only remove worktree)
        #[arg(short = 'k', long)]
        keep_branch: bool,

        /// Also delete the remote branch
        #[arg(short = 'r', long)]
        delete_remote: bool,

        /// Force remove: also bypasses the busy-detection gate (skips the
        /// "worktree is in use" check and deletes anyway)
        #[arg(short, long, conflicts_with = "no_force")]
        force: bool,

        /// Don't use --force flag
        #[arg(long)]
        no_force: bool,

        /// Resolve target as worktree name (instead of branch)
        #[arg(short, long)]
        worktree: bool,

        /// Resolve target as branch name (instead of worktree)
        #[arg(short, long, conflicts_with = "worktree")]
        branch: bool,
    },

    /// List all worktrees
    #[command(alias = "ls")]
    List {
        #[command(flatten)]
        cache: CacheControl,
    },

    /// Batch cleanup of worktrees
    ///
    /// Note: `--no-cache` only affects the interactive listing path inside `clean`
    /// (which calls `get_worktree_status`). Merge/age-based deletion logic in `clean`
    /// uses git directly and does not consult the PR cache.
    Clean {
        #[command(flatten)]
        cache: CacheControl,

        /// Delete worktrees for branches already merged to base
        #[arg(long)]
        merged: bool,

        /// Delete worktrees older than duration (e.g., 7, 30d, 2w, 1m)
        #[arg(long, value_name = "DURATION", value_parser = parse_duration_days)]
        older_than: Option<u64>,

        /// Interactive selection UI
        #[arg(short, long)]
        interactive: bool,

        /// Show what would be deleted without deleting
        #[arg(long)]
        dry_run: bool,

        /// Bypass the busy-detection gate: delete busy worktrees too
        /// (default: skip worktrees another session is using)
        #[arg(short, long)]
        force: bool,
    },

    /// Display worktree hierarchy as a tree
    Tree {
        #[command(flatten)]
        cache: CacheControl,
    },

    /// Show worktree statistics
    Stats {
        #[command(flatten)]
        cache: CacheControl,
    },

    /// Compare two branches
    Diff {
        /// First branch
        branch1: String,
        /// Second branch
        branch2: String,
        /// Show statistics only
        #[arg(short, long)]
        summary: bool,
        /// Show changed files only
        #[arg(short, long)]
        files: bool,
    },

    /// Sync worktree with base branch
    Sync {
        /// Branch name (default: current worktree)
        branch: Option<String>,

        /// Sync all worktrees
        #[arg(long)]
        all: bool,

        /// Only fetch updates without rebasing
        #[arg(long)]
        fetch_only: bool,

        /// Use AI to resolve merge conflicts
        #[arg(long)]
        ai_merge: bool,

        /// Resolve target as worktree name (instead of branch)
        #[arg(short, long)]
        worktree: bool,

        /// Resolve target as branch name (instead of worktree)
        #[arg(short, long, conflicts_with = "worktree")]
        by_branch: bool,
    },

    /// Change base branch for a worktree
    ChangeBase {
        /// New base branch
        new_base: String,
        /// Branch name (default: current worktree)
        branch: Option<String>,

        /// Dry run (show what would happen)
        #[arg(long)]
        dry_run: bool,

        /// Interactive rebase
        #[arg(short, long)]
        interactive: bool,

        /// Resolve target as worktree name (instead of branch)
        #[arg(short, long)]
        worktree: bool,

        /// Resolve target as branch name (instead of worktree)
        #[arg(short, long, conflicts_with = "worktree")]
        by_branch: bool,
    },

    /// Configuration management
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Backup and restore worktrees
    Backup {
        #[command(subcommand)]
        action: BackupAction,
    },

    /// Stash management (worktree-aware)
    Stash {
        #[command(subcommand)]
        action: StashAction,
    },

    /// Manage lifecycle hooks
    Hook {
        #[command(subcommand)]
        action: HookAction,
    },

    /// Export worktree configuration to a file
    Export {
        /// Output file path
        #[arg(short, long)]
        output: Option<String>,
    },

    /// Import worktree configuration from a file
    Import {
        /// Path to the configuration file to import
        import_file: String,

        /// Apply the imported configuration (default: preview only)
        #[arg(long)]
        apply: bool,
    },

    /// Scan for repositories (global mode)
    Scan {
        /// Base directory to scan (default: home directory)
        #[arg(short, long, value_hint = ValueHint::DirPath)]
        dir: Option<std::path::PathBuf>,
    },

    /// Clean up stale registry entries (global mode)
    Prune,

    /// Run diagnostics
    Doctor,

    /// Check for updates / upgrade
    Upgrade,

    /// Install Claude Code skill for worktree task delegation
    #[command(name = "setup-claude")]
    SetupClaude,

    /// Interactive shell integration setup
    ShellSetup,

    /// [Internal] Get worktree path for a branch
    #[command(name = "_path", hide = true)]
    Path {
        /// Branch name
        branch: Option<String>,

        /// List branch names (for tab completion)
        #[arg(long)]
        list_branches: bool,

        /// Interactive worktree selection
        #[arg(short, long)]
        interactive: bool,
    },

    /// Generate shell function for gw-cd / cw-cd
    #[command(name = "_shell-function", hide = true)]
    ShellFunction {
        /// Shell type: bash, zsh, fish, or powershell
        shell: String,
    },

    /// List config keys (for tab completion)
    #[command(name = "_config-keys", hide = true)]
    ConfigKeys,

    /// Refresh update cache (background process)
    #[command(name = "_update-cache", hide = true)]
    UpdateCache,

    /// List terminal launch method values (for tab completion)
    #[command(name = "_term-values", hide = true)]
    TermValues,

    /// List preset names (for tab completion)
    #[command(name = "_preset-names", hide = true)]
    PresetNames,

    /// List hook event names (for tab completion)
    #[command(name = "_hook-events", hide = true)]
    HookEvents,
}

#[derive(Subcommand, Debug)]
pub enum ConfigAction {
    /// Show current configuration summary
    Show,
    /// List all configuration keys, values, and descriptions
    #[command(alias = "ls")]
    List,
    /// Get a configuration value
    Get {
        /// Dot-separated config key (e.g., ai_tool.command)
        #[arg(value_parser = parse_config_key)]
        key: String,
    },
    /// Set a configuration value
    Set {
        /// Dot-separated config key (e.g., ai_tool.command)
        #[arg(value_parser = parse_config_key)]
        key: String,
        /// Value to set
        value: String,
    },
    /// Use a predefined AI tool preset
    UsePreset {
        /// Preset name (e.g., claude, codex, no-op)
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::PRESET_NAMES))]
        name: String,
    },
    /// List available presets
    ListPresets,
    /// Reset configuration to defaults
    Reset,
}

#[derive(Subcommand, Debug)]
pub enum BackupAction {
    /// Create backup of worktree(s) using git bundle
    Create {
        /// Branch name to backup (default: current worktree)
        branch: Option<String>,

        /// Backup all worktrees
        #[arg(long)]
        all: bool,

        /// Output directory for backups
        #[arg(short, long)]
        output: Option<String>,
    },
    /// List available backups
    List {
        /// Filter by branch name
        branch: Option<String>,

        /// Show all backups (not just current repo)
        #[arg(short, long)]
        all: bool,
    },
    /// Restore worktree from backup
    Restore {
        /// Branch name to restore
        branch: String,

        /// Custom path for restored worktree
        #[arg(short, long)]
        path: Option<String>,

        /// Backup ID (timestamp) to restore (default: latest)
        #[arg(long)]
        id: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum StashAction {
    /// Save changes in current worktree to stash
    Save {
        /// Optional message to describe the stash
        message: Option<String>,
    },
    /// List all stashes organized by worktree/branch
    List,
    /// Apply a stash to a different worktree
    Apply {
        /// Branch name of worktree to apply stash to
        target_branch: String,

        /// Stash reference (default: stash@{0})
        #[arg(short, long, default_value = "stash@{0}")]
        stash: String,
    },
}

#[derive(Subcommand, Debug)]
pub enum HookAction {
    /// Add a new hook for an event
    Add {
        /// Hook event (e.g., worktree.post_create, merge.pre)
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::HOOK_EVENTS))]
        event: String,
        /// Shell command to execute
        command: String,
        /// Custom hook identifier
        #[arg(long)]
        id: Option<String>,
        /// Human-readable description
        #[arg(short, long)]
        description: Option<String>,
    },
    /// Remove a hook
    Remove {
        /// Hook event
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::HOOK_EVENTS))]
        event: String,
        /// Hook identifier to remove
        hook_id: String,
    },
    /// List all hooks
    List {
        /// Filter by event
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::HOOK_EVENTS))]
        event: Option<String>,
    },
    /// Enable a disabled hook
    Enable {
        /// Hook event
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::HOOK_EVENTS))]
        event: String,
        /// Hook identifier
        hook_id: String,
    },
    /// Disable a hook without removing it
    Disable {
        /// Hook event
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::HOOK_EVENTS))]
        event: String,
        /// Hook identifier
        hook_id: String,
    },
    /// Manually run all hooks for an event
    Run {
        /// Hook event to run
        #[arg(value_parser = clap::builder::PossibleValuesParser::new(crate::constants::HOOK_EVENTS))]
        event: String,
        /// Show what would be executed without running
        #[arg(long)]
        dry_run: bool,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    /// Assert that `gw clean --no-cache` parses correctly. Pins the CacheControl
    /// flag on Clean so accidental removal breaks the test.
    #[test]
    fn clean_accepts_no_cache_flag() {
        let cli = Cli::try_parse_from(["gw", "clean", "--no-cache"]).expect("parses");
        let Some(Commands::Clean { cache, .. }) = cli.command else {
            panic!("expected Clean variant, got {:?}", cli.command);
        };
        assert!(cache.no_cache);
    }
}