deadbranch 0.1.3

Clean up stale git branches safely
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! deadbranch - Clean up stale git branches safely

mod backup;
mod branch;
mod cli;
mod config;
mod error;
mod git;
mod stats;
mod ui;

use anyhow::{Context, Result};
use chrono::Utc;
use clap::{CommandFactory, Parser};
use clap_complete::generate;
use std::fs;
use std::io::Write;

use branch::BranchFilter;
use cli::{BackupAction, Cli, Commands, ConfigAction};
use config::Config;

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Check if we're in a git repository (except for config, backup, and completions commands)
    if !matches!(
        cli.command,
        Commands::Config { .. } | Commands::Backup { .. } | Commands::Completions { .. }
    ) && !git::is_git_repository()
    {
        ui::error("Not a git repository (or any parent up to mount point)");
        std::process::exit(1);
    }

    match cli.command {
        Commands::List {
            days,
            local,
            remote,
            merged,
        } => cmd_list(days, local, remote, merged),

        Commands::Clean {
            days,
            merged,
            force,
            dry_run,
            local,
            remote,
            yes,
        } => cmd_clean(days, merged, force, dry_run, local, remote, yes),

        Commands::Config { action } => cmd_config(action),

        Commands::Backup { action } => cmd_backup(action),

        Commands::Stats { days } => cmd_stats(days),

        Commands::Completions { shell } => {
            generate(
                shell,
                &mut Cli::command(),
                "deadbranch",
                &mut std::io::stdout(),
            );
            Ok(())
        }
    }
}

/// List stale branches
fn cmd_list(
    days: Option<u32>,
    local_only: bool,
    remote_only: bool,
    merged_only: bool,
) -> Result<()> {
    let config = Config::load()?;

    // Use CLI value if provided, otherwise use config default
    let min_age = days.unwrap_or(config.general.default_days);

    // Get default branch for merge detection
    let default_branch = config
        .branches
        .default_branch
        .clone()
        .unwrap_or_else(|| git::get_default_branch().unwrap_or_else(|_| "main".to_string()));

    ui::info(&format!(
        "Using '{}' as the default branch for merge detection",
        default_branch
    ));

    // List all branches
    let spinner = ui::spinner("Loading branches...");
    let all_branches = git::list_branches(&default_branch)?;
    spinner.finish_and_clear();

    // Filter branches
    let filter = BranchFilter {
        min_age_days: min_age,
        local_only,
        remote_only,
        merged_only,
        protected_branches: config.branches.protected,
        exclude_patterns: config.branches.exclude_patterns,
    };

    let mut branches: Vec<_> = all_branches
        .into_iter()
        .filter(|b| filter.matches(b))
        .collect();

    // Sort: unmerged first, then by age (oldest first)
    branch::sort_branches(&mut branches);

    // Separate local and remote for grouped display
    let mut local: Vec<_> = branches.iter().filter(|b| !b.is_remote).cloned().collect();
    let mut remote: Vec<_> = branches.iter().filter(|b| b.is_remote).cloned().collect();

    // Sort each group separately
    branch::sort_branches(&mut local);
    branch::sort_branches(&mut remote);

    // Display in table format
    if !local.is_empty() {
        ui::display_branches(&local, "Local Branches:");
    }
    if !remote.is_empty() {
        ui::display_branches(&remote, "Remote Branches:");
    }
    if local.is_empty() && remote.is_empty() {
        ui::info("No stale branches found.");
    }

    Ok(())
}

/// Clean (delete) stale branches
fn cmd_clean(
    days: Option<u32>,
    merged: bool,
    force: bool,
    dry_run: bool,
    local_only: bool,
    remote_only: bool,
    skip_confirm: bool,
) -> Result<()> {
    let config = Config::load()?;

    // Use CLI value if provided, otherwise use config default
    let min_age = days.unwrap_or(config.general.default_days);

    // Get default branch for merge detection
    let default_branch = config
        .branches
        .default_branch
        .clone()
        .unwrap_or_else(|| git::get_default_branch().unwrap_or_else(|_| "main".to_string()));

    // By default, only delete merged branches unless --force is used
    let merged_only = merged || !force;

    // Create filter - by default, show both local and remote branches
    // Use --local or --remote to filter to only one type
    let filter = BranchFilter {
        min_age_days: min_age,
        local_only,
        remote_only,
        merged_only,
        protected_branches: config.branches.protected.clone(),
        exclude_patterns: config.branches.exclude_patterns,
    };

    // List all branches
    let spinner = ui::spinner("Loading branches...");
    let all_branches = git::list_branches(&default_branch)?;
    spinner.finish_and_clear();

    // Filter branches
    let mut branches: Vec<_> = all_branches
        .into_iter()
        .filter(|b| filter.matches(b))
        .collect();

    // Sort: unmerged first, then by age (oldest first)
    branch::sort_branches(&mut branches);

    if branches.is_empty() {
        ui::info("No branches to delete.");
        return Ok(());
    }

    // Separate local and remote
    let mut local_branches: Vec<_> = branches.iter().filter(|b| !b.is_remote).cloned().collect();
    let mut remote_branches: Vec<_> = branches.iter().filter(|b| b.is_remote).cloned().collect();

    // Sort each group separately
    branch::sort_branches(&mut local_branches);
    branch::sort_branches(&mut remote_branches);

    if dry_run {
        // For dry-run, show all tables upfront
        if !local_branches.is_empty() {
            let title = format!(
                "Local {} to Delete:",
                ui::pluralize_branch_cap(local_branches.len())
            );
            ui::display_branches(&local_branches, &title);
        }
        if !remote_branches.is_empty() {
            let title = format!(
                "Remote {} to Delete:",
                ui::pluralize_branch_cap(remote_branches.len())
            );
            ui::display_branches(&remote_branches, &title);
        }

        ui::print_dry_run_header();

        for branch in &local_branches {
            let flag = if force || branch.is_merged {
                "-d"
            } else {
                "-D"
            };
            ui::print_dry_run_command(&format!("git branch {} {}", flag, branch.name));
        }

        for branch in &remote_branches {
            let name = branch.name.strip_prefix("origin/").unwrap_or(&branch.name);
            ui::print_dry_run_command(&format!("git push origin --delete {}", name));
        }

        ui::print_dry_run_footer();
        return Ok(());
    }

    // Handle local branches - show table right before confirmation
    if !local_branches.is_empty() {
        let title = format!(
            "Local {} to Delete:",
            ui::pluralize_branch_cap(local_branches.len())
        );
        ui::display_branches(&local_branches, &title);

        if skip_confirm || ui::confirm_local_deletion(&local_branches) {
            delete_branches_with_backup(&local_branches, force)?;
        } else {
            println!();
            ui::info("Skipped local branch deletion.");
        }
    }

    // Handle remote branches - show table as part of the warning
    if !remote_branches.is_empty() {
        // Add visual separation if we just handled local branches
        if !local_branches.is_empty() {
            println!();
            println!("{}", console::style("".repeat(50)).dim());
            println!();
        }

        // First, fetch and prune to ensure we have accurate data
        let spinner = ui::spinner("Fetching remote to ensure data is up to date...");
        match git::fetch_and_prune() {
            Ok(()) => ui::spinner_success(&spinner, "Remote data is up to date"),
            Err(e) => {
                ui::spinner_warn(&spinner, "Could not fetch remote");
                ui::warning(&format!("  {}", e));
                ui::warning("  Remote branch data may be stale.");
            }
        }

        // Show table and get confirmation
        let title = format!(
            "Remote {} to Delete:",
            ui::pluralize_branch_cap(remote_branches.len())
        );
        ui::display_branches(&remote_branches, &title);

        if skip_confirm || ui::confirm_remote_deletion(&remote_branches) {
            delete_remote_branches_with_backup(&remote_branches)?;
        } else {
            println!();
            ui::info("Skipped remote branch deletion.");
        }
    }

    Ok(())
}

/// Delete local branches and create backup file
fn delete_branches_with_backup(branches: &[branch::Branch], force: bool) -> Result<()> {
    let backup = create_backup_file(branches)?;
    let branch_word = ui::pluralize_branch(branches.len());

    // Visual separation after confirmation
    println!();
    println!("Deleting local {}...", branch_word);

    let mut deleted = 0;
    let mut failed = 0;

    for branch in branches {
        match git::delete_local_branch(&branch.name, force) {
            Ok(()) => {
                println!("  {} {}", console::style("").green(), branch.name);
                deleted += 1;
            }
            Err(e) => {
                println!("  {} {} ({})", console::style("").red(), branch.name, e);
                failed += 1;
            }
        }
    }

    // Summary footer
    println!();
    let branch_word = ui::pluralize_branch(deleted);
    if failed == 0 {
        ui::success(&format!("Deleted {} local {}", deleted, branch_word));
    } else {
        ui::warning(&format!(
            "Deleted {} local {}, {} failed",
            deleted, branch_word, failed
        ));
    }
    println!(
        "  {} Backup: {}",
        console::style("").dim(),
        console::style(&backup).dim()
    );

    Ok(())
}

/// Delete remote branches and create backup file
fn delete_remote_branches_with_backup(branches: &[branch::Branch]) -> Result<()> {
    let backup = create_backup_file(branches)?;
    let branch_word = ui::pluralize_branch(branches.len());

    // Visual separation after confirmation
    println!();
    println!("Deleting remote {}...", branch_word);

    let mut deleted = 0;
    let mut failed = 0;

    for branch in branches {
        match git::delete_remote_branch(&branch.name) {
            Ok(()) => {
                println!("  {} {}", console::style("").green(), branch.name);
                deleted += 1;
            }
            Err(e) => {
                println!("  {} {} ({})", console::style("").red(), branch.name, e);
                failed += 1;
            }
        }
    }

    // Summary footer
    println!();
    let branch_word = ui::pluralize_branch(deleted);
    if failed == 0 {
        ui::success(&format!("Deleted {} remote {}", deleted, branch_word));
    } else {
        ui::warning(&format!(
            "Deleted {} remote {}, {} failed",
            deleted, branch_word, failed
        ));
    }
    println!(
        "  {} Backup: {}",
        console::style("").dim(),
        console::style(&backup).dim()
    );

    Ok(())
}

/// Create a backup file with branch SHAs for potential restoration
/// Saves to ~/.deadbranch/backups/<repo-name>/backup-<timestamp>.txt
fn create_backup_file(branches: &[branch::Branch]) -> Result<String> {
    let repo_name = Config::get_repo_name();
    let backup_dir = Config::repo_backup_dir(&repo_name)?;

    // Create backup directory if it doesn't exist
    fs::create_dir_all(&backup_dir)?;

    let timestamp = Utc::now().format("%Y%m%d-%H%M%S");
    let filename = format!("backup-{}.txt", timestamp);
    let backup_path = backup_dir.join(&filename);

    let mut file = fs::File::create(&backup_path)?;

    writeln!(file, "# deadbranch backup")?;
    writeln!(file, "# Created: {}", Utc::now().to_rfc3339())?;
    writeln!(file, "# Repository: {}", repo_name)?;
    writeln!(
        file,
        "# Working directory: {}",
        std::env::current_dir()?.display()
    )?;
    writeln!(file, "#")?;
    writeln!(file, "# To restore a branch, run the git command shown")?;
    writeln!(file, "#")?;
    writeln!(file)?;

    for branch in branches {
        let sha =
            git::get_branch_sha(&branch.name).unwrap_or_else(|_| branch.last_commit_sha.clone());
        let restore_name = if branch.is_remote {
            branch.name.strip_prefix("origin/").unwrap_or(&branch.name)
        } else {
            &branch.name
        };
        writeln!(file, "# {}", branch.name)?;
        writeln!(file, "git branch {} {}", restore_name, sha)?;
        writeln!(file)?;
    }

    Ok(backup_path.display().to_string())
}

/// Handle config subcommands
fn cmd_config(action: ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Show => {
            let config = Config::load()?;
            let config_path = Config::config_path()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|_| "(unknown)".to_string());

            ui::display_config(
                config.general.default_days,
                &config.branches.protected,
                &config.branches.exclude_patterns,
                config.branches.default_branch.as_deref(),
                &config_path,
            );
        }

        ConfigAction::Set { key, values } => {
            let mut config = Config::load()?;
            config.set(&key, &values)?;
            config.save()?;

            // Format display based on single value or list
            let display_value = if values.len() == 1 {
                values[0].clone()
            } else {
                values.join(", ")
            };
            ui::success(&format!("Set {} = {}", key, display_value));
        }

        ConfigAction::Edit => {
            // Ensure config file exists
            let _ = Config::load()?;
            let config_path = Config::config_path()?;

            // Get editor from $EDITOR or $VISUAL, fallback to common editors
            let editor = std::env::var("EDITOR")
                .or_else(|_| std::env::var("VISUAL"))
                .unwrap_or_else(|_| {
                    // Try common editors
                    if which::which("nano").is_ok() {
                        "nano".to_string()
                    } else if which::which("vim").is_ok() {
                        "vim".to_string()
                    } else if which::which("vi").is_ok() {
                        "vi".to_string()
                    } else {
                        "nano".to_string() // Default fallback
                    }
                });

            ui::info(&format!(
                "Opening {} in {}...",
                config_path.display(),
                editor
            ));

            let status = std::process::Command::new(&editor)
                .arg(&config_path)
                .status()
                .with_context(|| format!("Failed to open editor: {}", editor))?;

            if status.success() {
                ui::success("Config file saved");
            } else {
                ui::warning("Editor exited with non-zero status");
            }
        }

        ConfigAction::Reset => {
            if ui::confirm("Reset configuration to defaults?", false) {
                let config = Config::default();
                config.save()?;
                ui::success("Configuration reset to defaults");
            } else {
                ui::info("Cancelled");
            }
        }
    }

    Ok(())
}

/// Show repository branch statistics
fn cmd_stats(days: Option<u32>) -> Result<()> {
    let config = Config::load()?;
    let min_age = days.unwrap_or(config.general.default_days);

    let default_branch = config
        .branches
        .default_branch
        .clone()
        .unwrap_or_else(|| git::get_default_branch().unwrap_or_else(|_| "main".to_string()));

    ui::info(&format!(
        "Using '{}' as the default branch for merge detection",
        default_branch
    ));

    let spinner = ui::spinner("Loading branches...");
    let all_branches = git::list_branches(&default_branch)?;
    spinner.finish_and_clear();

    // Apply the same visibility rules as list/clean: respect protected and
    // exclude_patterns, but no age filter — stats covers all visible branches.
    let filter = BranchFilter {
        min_age_days: 0,
        local_only: false,
        remote_only: false,
        merged_only: false,
        protected_branches: config.branches.protected,
        exclude_patterns: config.branches.exclude_patterns,
    };

    let branches: Vec<_> = all_branches
        .into_iter()
        .filter(|b| filter.matches(b))
        .collect();

    let repo_stats = stats::compute_stats(&branches, min_age);
    ui::display_repo_stats(&repo_stats);

    Ok(())
}

/// Handle backup subcommands
fn cmd_backup(action: BackupAction) -> Result<()> {
    match action {
        BackupAction::List { current, repo } => {
            // Determine which repo to show (if any specific one)
            let target_repo = if current {
                // Check if we're in a git repo for --current
                if !git::is_git_repository() {
                    ui::error("Not a git repository (or any parent up to mount point)");
                    ui::info("Use 'deadbranch backup list' without --current to see all backups.");
                    std::process::exit(1);
                }
                Some(Config::get_repo_name())
            } else {
                repo
            };

            if let Some(repo_name) = target_repo {
                // Show detailed view for specific repo
                let backups = backup::list_repo_backups(&repo_name)?;

                if backups.is_empty() {
                    ui::info(&format!("No backups found for repository '{}'", repo_name));
                    println!();
                    println!(
                        "  {} Backups are created automatically when running 'deadbranch clean'.",
                        console::style("").dim()
                    );
                } else {
                    ui::display_repo_backups(&repo_name, &backups);
                }
            } else {
                // Show summary of all repos
                let all_backups = backup::list_all_backups()?;

                if all_backups.is_empty() {
                    ui::info("No backups found.");
                    println!();
                    println!(
                        "  {} Backups are created automatically when running 'deadbranch clean'.",
                        console::style("").dim()
                    );
                } else {
                    ui::display_all_backups(&all_backups);
                }
            }
        }

        BackupAction::Stats => {
            let stats = backup::get_backup_stats()?;
            ui::display_backup_stats(&stats);
        }

        BackupAction::Restore {
            branch,
            from,
            r#as,
            force,
        } => {
            // Restore requires being in a git repository
            if !git::is_git_repository() {
                ui::error("Not a git repository (or any parent up to mount point)");
                std::process::exit(1);
            }

            match backup::restore_branch(&branch, from.as_deref(), r#as.as_deref(), force) {
                Ok(result) => {
                    ui::display_restore_success(&result);
                }
                Err(e) => {
                    ui::display_restore_error(&e, &branch);
                    std::process::exit(1);
                }
            }
        }

        BackupAction::Clean {
            current,
            repo,
            keep,
            dry_run,
            yes,
        } => {
            // Determine target repo
            let repo_name = if current {
                if !git::is_git_repository() {
                    ui::error("Not a git repository (or any parent up to mount point)");
                    ui::info("Use --repo <name> to specify a repository by name.");
                    std::process::exit(1);
                }
                Config::get_repo_name()
            } else if let Some(name) = repo {
                name
            } else {
                ui::error("Either --current or --repo <name> is required");
                std::process::exit(1);
            };

            // Get backups to clean
            let backups_to_clean = backup::get_backups_to_clean(&repo_name, keep)?;

            // Check if there are any backups at all for this repo
            let all_backups = backup::list_repo_backups(&repo_name)?;
            if all_backups.is_empty() {
                ui::display_no_backups_for_repo(&repo_name);
                return Ok(());
            }

            // Display what will be deleted
            ui::display_backups_to_clean(&repo_name, &backups_to_clean, keep, dry_run);

            if backups_to_clean.is_empty() {
                return Ok(());
            }

            if dry_run {
                let total_size: u64 = backups_to_clean.iter().map(|b| b.size_bytes).sum();
                ui::display_backup_clean_dry_run(backups_to_clean.len(), total_size);
                return Ok(());
            }

            // Confirm deletion unless --yes was provided
            let total_size: u64 = backups_to_clean.iter().map(|b| b.size_bytes).sum();
            if !yes && !ui::confirm_backup_clean(backups_to_clean.len(), total_size) {
                ui::info("Cancelled");
                return Ok(());
            }

            // Perform deletion
            let result = backup::delete_backups(&backups_to_clean)?;
            ui::display_backup_clean_success(&result);
        }
    }

    Ok(())
}